diff --git a/index.js b/index.js index 8bb9b3e..eaffa87 100644 --- a/index.js +++ b/index.js @@ -1,30 +1,38 @@ 'use strict'; -module.exports = function (ms) { - ms = ms || 0; - - var promise = new Promise(function (resolve) { - setTimeout(resolve, ms); - }); - - function thunk(result) { - return new Promise(function (resolve) { - setTimeout(function () { - resolve(result); - }, ms); - }); - } +module.exports = generate(true); +module.exports.resolve = module.exports; +module.exports.reject = generate(false); + +function generate(shouldResolve) { + return function (ms, value) { + ms = ms || 0; - thunk.then = promise.then.bind(promise); - thunk.catch = promise.catch.bind(promise); + function pickAction(resolve, reject) { + var action = shouldResolve ? resolve : reject; + if (arguments.length > 1) { + action = action.bind(null, value); + } - return thunk; -}; + return action; + } -module.exports.reject = function (ms, value) { - if (arguments.length > 1) { - return new Promise(function (resolve, reject) { - setTimeout(reject.bind(null, value), ms); + var promise = new Promise(function (resolve, reject) { + setTimeout(pickAction(resolve, reject), ms); }); - } - return module.exports.reject.bind(null, ms); -}; + + function thunk(result) { + promise.catch(noop); + value = value || result; + return new Promise(function (resolve, reject) { + setTimeout(pickAction(resolve, reject), ms); + }); + } + + thunk.then = promise.then.bind(promise); + thunk.catch = promise.catch.bind(promise); + + return thunk; + }; +} + +function noop() {} diff --git a/test.js b/test.js index f6e8fef..decaf68 100644 --- a/test.js +++ b/test.js @@ -4,14 +4,12 @@ import inRange from 'in-range'; import fn from './'; test('promise', async t => { - t.plan(1); const end = timeSpan(); await fn(50); t.true(inRange(end(), 30, 70), 'is delayed'); }); test('thunk', async t => { - t.plan(2); const end = timeSpan(); const result = await Promise.resolve('foo').then(fn(50)); t.true(inRange(end(), 30, 70), 'is delayed'); @@ -24,6 +22,16 @@ test('.reject() with two arguments', async t => { t.true(inRange(end(), 30, 70), 'is delayed'); }); +test('.reject() with two arguments (as a thunk)', async t => { + const end = timeSpan(); + await t.throws( + Promise.resolve('foo').then(fn.reject(50, new Error('bar'))), + 'bar', + 'promise is rejected with the resolution value' + ); + t.true(inRange(end(), 30, 70), 'is delayed'); +}); + test('.reject() with one argument (thunk)', async t => { const end = timeSpan(); await t.throws(