How to use async in figma.onClose()

Hello, I am a junior developer preparing to deploy a plugin. I look forward to your support.

My plugin creates nodes and stores their IDs. When the user closes the plugin, I use the figma.onClose() event listener to detect the close event and then use the getNodeById API to find and delete the nodes created by the plugin.

After adding documentAccess: dynamic-page in the manifest.json to prepare for deployment, I encountered a warning stating, “Error in getNodeById: Cannot call with documentAccess: dynamic-page. Use figma.getNodeByIdAsync instead.” Therefore, I switched to getNodeByIdAsync, but then I found out from the link below that asynchronous functions do not work within the callback of figma.onClose().

I am curious about how to resolve this issue. If there is no solution, I would like to know what other methods I could use to delete the nodes created by my plugin.

https://www.figma.com/plugin-docs/api/properties/figma-on/#close

You can’t use async methods in onClose as per documentation:

You should use this API only if strictly necessary, and run as little code as possible in the callback when doing so. When a user closes a plugin, they expect it to be closed immediately. Having long-running actions in the closing callback prevents the plugin for closing promptly.

This is also not the place to run any asynchronous actions (e.g. register callbacks, using await, etc). The plugin execution environment will be destroyed immediately when all the callbacks have returned, and further callbacks will not be called.

Regarding this:

Why do you do this? If nodes are created by the plugin, you already have access to them in the code (stored in variables or array).

Example:

let rect = figma.createRectangle()
rect.resize(50, 50)

// ...

figma.on('close', () => { rect.remove() })
1 Like

Thank you for your kindness. I apply your solution. Thanks :slight_smile: