简单的异步操作


¥Simple asynchronous operations

插件模块通常需要利用 libuv 中的异步助手作为其实现的一部分。这允许他们安排异步执行的工作,以便他们的方法可以在工作完成之前返回。这使他们能够避免阻止 Node.js 应用的整体执行。

¥Addon modules often need to leverage async helpers from libuv as part of their implementation. This allows them to schedule work to be executed asynchronously so that their methods can return in advance of the work being completed. This allows them to avoid blocking overall execution of the Node.js application.

Node-API 为这些支持功能提供了一个 ABI 稳定的接口,涵盖了最常见的异步用例。

¥Node-API provides an ABI-stable interface for these supporting functions which covers the most common asynchronous use cases.

Node-API 定义了用于管理异步工作者的 napi_async_work 结构。使用 napi_create_async_worknapi_delete_async_work 创建/删除实例。

¥Node-API defines the napi_async_work structure which is used to manage asynchronous workers. Instances are created/deleted with napi_create_async_work and napi_delete_async_work.

executecomplete 回调函数将分别在执行程序准备好执行和完成任务时调用。

¥The execute and complete callbacks are functions that will be invoked when the executor is ready to execute and when it completes its task respectively.

execute 函数应避免进行任何可能导致 JavaScript 执行或与 JavaScript 对象交互的 Node-API 调用。大多数情况下,任何需要进行 Node-API 调用的代码都应该在 complete 回调中进行。避免在执行回调中使用 napi_env 参数,因为它可能会执行 JavaScript。

¥The execute function should avoid making any Node-API calls that could result in the execution of JavaScript or interaction with JavaScript objects. Most often, any code that needs to make Node-API calls should be made in complete callback instead. Avoid using the napi_env parameter in the execute callback as it will likely execute JavaScript.

这些函数实现了以下接口:

¥These functions implement the following interfaces:

typedef void (*napi_async_execute_callback)(napi_env env,
                                            void* data);
typedef void (*napi_async_complete_callback)(napi_env env,
                                             napi_status status,
                                             void* data); 

调用这些方法时,传递的 data 参数将是传递给 napi_create_async_work 调用的插件提供的 void* 数据。

¥When these methods are invoked, the data parameter passed will be the addon-provided void* data that was passed into the napi_create_async_work call.

创建异步工作线程后,可以使用 napi_queue_async_work 函数排队等待执行:

¥Once created the async worker can be queued for execution using the napi_queue_async_work function:

napi_status napi_queue_async_work(node_api_basic_env env,
                                  napi_async_work work); 

如果需要在工作开始执行之前取消工作,则可以使用 napi_cancel_async_work

¥napi_cancel_async_work can be used if the work needs to be cancelled before the work has started execution.

调用 napi_cancel_async_work 后,将调用状态值为 napi_cancelledcomplete 回调。在 complete 回调调用之前不应删除该工作,即使它已被取消。

¥After calling napi_cancel_async_work, the complete callback will be invoked with a status value of napi_cancelled. The work should not be deleted before the complete callback invocation, even when it was cancelled.