node/test/addons-napi/test_promise/test.js
Gabriel Schulhof 7efb8f7619 n-api: implement promise
Promise is implemented as a pair of objects. `napi_create_promise()`
returns both a JavaScript promise and a newly allocated "deferred" in
its out-params. The deferred is linked to the promise such that the
deferred can be passed to `napi_resolve_deferred()` or
`napi_reject_deferred()` to reject/resolve the promise.

`napi_is_promise()` can be used to check if a `napi_value` is a native
promise - that is, a promise created by the underlying engine, rather
than a pure JS implementation of a promise.

PR-URL: https://github.com/nodejs/node/pull/14365
Fixes: https://github.com/nodejs/abi-stable-node/issues/242
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Timothy Gu <timothygu99@gmail.com>
2017-08-25 12:02:55 +03:00

61 lines
2.0 KiB
JavaScript

'use strict';
const common = require('../../common');
const test_promise = require(`./build/${common.buildType}/test_promise`);
const assert = require('assert');
let expected_result, promise;
// A resolution
expected_result = 42;
promise = test_promise.createPromise();
promise.then(
common.mustCall(function(result) {
assert.strictEqual(result, expected_result,
'promise resolved as expected');
}),
common.mustNotCall());
test_promise.concludeCurrentPromise(expected_result, true);
// A rejection
expected_result = 'It\'s not you, it\'s me.';
promise = test_promise.createPromise();
promise.then(
common.mustNotCall(),
common.mustCall(function(result) {
assert.strictEqual(result, expected_result,
'promise rejected as expected');
}));
test_promise.concludeCurrentPromise(expected_result, false);
// Chaining
promise = test_promise.createPromise();
promise.then(
common.mustCall(function(result) {
assert.strictEqual(result, 'chained answer',
'resolving with a promise chains properly');
}),
common.mustNotCall());
test_promise.concludeCurrentPromise(Promise.resolve('chained answer'), true);
assert.strictEqual(test_promise.isPromise(promise), true,
'natively created promise is recognized as a promise');
assert.strictEqual(test_promise.isPromise(Promise.reject(-1)), true,
'Promise created with JS is recognized as a promise');
assert.strictEqual(test_promise.isPromise(2.4), false,
'Number is recognized as not a promise');
assert.strictEqual(test_promise.isPromise('I promise!'), false,
'String is recognized as not a promise');
assert.strictEqual(test_promise.isPromise(undefined), false,
'undefined is recognized as not a promise');
assert.strictEqual(test_promise.isPromise(null), false,
'null is recognized as not a promise');
assert.strictEqual(test_promise.isPromise({}), false,
'an object is recognized as not a promise');