1# AsyncContext 2 3The [Napi::AsyncWorker](async_worker.md) class may not be appropriate for every 4scenario. When using any other async mechanism, introducing a new class 5`Napi::AsyncContext` is necessary to ensure an async operation is properly 6tracked by the runtime. The `Napi::AsyncContext` class can be passed to 7[Napi::Function::MakeCallback()](function.md) method to properly restore the 8correct async execution context. 9 10## Methods 11 12### Constructor 13 14Creates a new `Napi::AsyncContext`. 15 16```cpp 17explicit Napi::AsyncContext::AsyncContext(napi_env env, const char* resource_name); 18``` 19 20- `[in] env`: The environment in which to create the `Napi::AsyncContext`. 21- `[in] resource_name`: Null-terminated strings that represents the 22identifier for the kind of resource that is being provided for diagnostic 23information exposed by the `async_hooks` API. 24 25### Constructor 26 27Creates a new `Napi::AsyncContext`. 28 29```cpp 30explicit Napi::AsyncContext::AsyncContext(napi_env env, const char* resource_name, const Napi::Object& resource); 31``` 32 33- `[in] env`: The environment in which to create the `Napi::AsyncContext`. 34- `[in] resource_name`: Null-terminated strings that represents the 35identifier for the kind of resource that is being provided for diagnostic 36information exposed by the `async_hooks` API. 37- `[in] resource`: Object associated with the asynchronous operation that 38will be passed to possible `async_hooks`. 39 40### Destructor 41 42The `Napi::AsyncContext` to be destroyed. 43 44```cpp 45virtual Napi::AsyncContext::~AsyncContext(); 46``` 47 48### Env 49 50Requests the environment in which the async context has been initially created. 51 52```cpp 53Napi::Env Env() const; 54``` 55 56Returns the `Napi::Env` environment in which the async context has been created. 57 58## Operator 59 60```cpp 61Napi::AsyncContext::operator napi_async_context() const; 62``` 63 64Returns the Node-API `napi_async_context` wrapped by the `Napi::AsyncContext` 65object. This can be used to mix usage of the C Node-API and node-addon-api. 66 67## Example 68 69```cpp 70#include "napi.h" 71 72void MakeCallbackWithAsyncContext(const Napi::CallbackInfo& info) { 73 Napi::Function callback = info[0].As<Napi::Function>(); 74 Napi::Object resource = info[1].As<Napi::Object>(); 75 76 // Create a new async context instance. 77 Napi::AsyncContext context(info.Env(), "async_context_test", resource); 78 79 // Invoke the callback with the async context instance. 80 callback.MakeCallback(Napi::Object::New(info.Env()), 81 std::initializer_list<napi_value>{}, context); 82 83 // The async context instance is automatically destroyed here because it's 84 // block-scope like `Napi::HandleScope`. 85} 86``` 87