diff --git a/lib/create-promise.js b/lib/create-promise.js new file mode 100644 index 0000000..c32eb87 --- /dev/null +++ b/lib/create-promise.js @@ -0,0 +1,33 @@ +'use strict' + +/** + * @typedef PromiseObject + * @property {Promise} promise + * @property {PromiseConstructor["resolve"]} resolve + * @property {PromiseConstructor["reject"]} reject + */ + +/** + * @returns {PromiseObject} + */ +function createPromise () { + /** + * @type {PromiseObject} + */ + const obj = { + resolve: null, + reject: null, + promise: null + } + + obj.promise = new Promise((resolve, reject) => { + obj.resolve = resolve + obj.reject = reject + }) + + return obj +} + +module.exports = { + createPromise +} diff --git a/plugin.js b/plugin.js index e38f558..975b477 100644 --- a/plugin.js +++ b/plugin.js @@ -4,20 +4,10 @@ const fastq = require('fastq') const EE = require('events').EventEmitter const inherits = require('util').inherits const { debug } = require('./lib/debug') +const { createPromise } = require('./lib/create-promise') const { AVV_ERR_READY_TIMEOUT } = require('./lib/errors') const { getPluginName } = require('./lib/get-plugin-name') -function promise () { - const obj = {} - - obj.promise = new Promise((resolve, reject) => { - obj.resolve = resolve - obj.reject = reject - }) - - return obj -} - function Plugin (parent, func, options, isAfter, timeout) { this.started = false this.func = func @@ -144,7 +134,7 @@ Plugin.prototype.loadedSoFar = function () { let res if (!this._promise) { - this._promise = promise() + this._promise = createPromise() res = this._promise.promise if (!this.server) { diff --git a/test/lib/create-promise.test.js b/test/lib/create-promise.test.js new file mode 100644 index 0000000..99ed5c6 --- /dev/null +++ b/test/lib/create-promise.test.js @@ -0,0 +1,55 @@ +'use strict' + +const { test } = require('tap') +const { createPromise } = require('../../lib/create-promise') + +test('createPromise() returns an object', (t) => { + t.plan(3) + t.type(createPromise(), 'object') + t.equal(Array.isArray(createPromise()), false) + t.notOk(Array.isArray(createPromise() !== null)) +}) + +test('createPromise() returns an attribute with attribute resolve', (t) => { + t.plan(1) + t.ok('resolve' in createPromise()) +}) + +test('createPromise() returns an attribute with attribute reject', (t) => { + t.plan(1) + t.ok('reject' in createPromise()) +}) + +test('createPromise() returns an attribute with attribute createPromise', (t) => { + t.plan(1) + t.ok('promise' in createPromise()) +}) + +test('when resolve is called, createPromise attribute is resolved', (t) => { + t.plan(1) + const p = createPromise() + + p.promise + .then(() => { + t.pass() + }) + .catch(() => { + t.fail() + }) + p.resolve() +}) + +test('when reject is called, createPromise attribute is rejected', (t) => { + t.plan(1) + const p = createPromise() + + p.promise + .then(() => { + t.fail() + }) + .catch(() => { + t.pass() + }) + + p.reject() +})