N-API provides facilities for creating Promise objects as described in [Section 25.4][] of the ECMA specification. It implements promises as a pair of objects. When a promise is created by napi_create_promise(), a “deferred” object is created and returned alongside the Promise. The deferred object is bound to the created Promise and is the only means to resolve or reject the Promise using napi_resolve_deferred() or napi_reject_deferred(). The deferred object that is created by napi_create_promise() is freed by napi_resolve_deferred() or napi_reject_deferred(). The Promise object may be returned to JavaScript where it can be used in the usual fashion.

    For example, to create a promise and pass it to an asynchronous worker:

    1. napi_deferred deferred;
    2. napi_value promise;
    3. napi_status status;
    4. // Create the promise.
    5. status = napi_create_promise(env, &deferred, &promise);
    6. if (status != napi_ok) return NULL;
    7. // Pass the deferred to a function that performs an asynchronous action.
    8. do_something_asynchronous(deferred);
    9. // Return the promise to JS
    10. return promise;

    The above function do_something_asynchronous() would perform its asynchronous action and then it would resolve or reject the deferred, thereby concluding the promise and freeing the deferred:

    1. napi_deferred deferred;
    2. napi_value undefined;
    3. napi_status status;
    4. // Create a value with which to conclude the deferred.
    5. status = napi_get_undefined(env, &undefined);
    6. if (status != napi_ok) return NULL;
    7. // Resolve or reject the promise associated with the deferred depending on
    8. // whether the asynchronous action succeeded.
    9. if (asynchronous_action_succeeded) {
    10. status = napi_resolve_deferred(env, deferred, undefined);
    11. } else {
    12. status = napi_reject_deferred(env, deferred, undefined);
    13. }
    14. if (status != napi_ok) return NULL;
    15. // At this point the deferred has been freed, so we should assign NULL to it.
    16. deferred = NULL;