Published on

useCallback 执行异步操作

Authors
  • avatar
    Name
    Shelton Ma
    Twitter

问题现象(What Happened)

useCallback 没按顺序执行, 在 executeDuplicate, 当执行editor?.onCopy(); editor?.onPaste(); 发现异步执行有问题, 如何确保顺序执行?

问题原因(Why It Happened)

useCallback does not inherently guarantee completion; it just memoizes the function.

解决方案(How to Fix It)

// src/features/editor/components/toolbar.tsx
...
const executeDuplicate = useCallback(async () => {
  await editor?.onCopy();
  await editor?.onPaste();
}, [editor]);
...
<Button onClick={() => executeDuplicate()} size="icon" variant="ghost">
  <Copy className="size-4" />
</Button>