简单的异步操作


【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 回调中进行。避免在 execute 回调中使用 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 参数将是由插件提供的 void* 数据,该数据在 napi_create_async_work 调用时传入。

【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 之后,complete 回调将以 napi_cancelled 状态值被调用。即使工作已被取消,也不应在 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.】