Cancel any cancelable input promises (#3)

This commit is contained in:
Kevin Mårtensson 2017-11-19 10:33:44 +01:00 committed by Sindre Sorhus
parent 14d97b13fd
commit 0324327342
3 changed files with 19 additions and 0 deletions

View File

@ -22,6 +22,10 @@ module.exports = (promise, ms, fallback) => new Promise((resolve, reject) => {
const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${ms} milliseconds`;
const err = fallback instanceof Error ? fallback : new TimeoutError(message);
if (typeof promise.cancel === 'function') {
promise.cancel();
}
reject(err);
}, ms);

View File

@ -37,6 +37,7 @@
"devDependencies": {
"ava": "*",
"delay": "^2.0.0",
"p-cancelable": "^0.3.0",
"xo": "*"
}
}

14
test.js
View File

@ -1,5 +1,6 @@
import test from 'ava';
import delay from 'delay';
import PCancelable from 'p-cancelable';
import m from '.';
const fixture = Symbol('fixture');
@ -30,3 +31,16 @@ test('fallback argument', async t => {
await t.throws(m(delay(200), 50, new RangeError('cake')), RangeError);
await t.throws(m(delay(200), 50, () => Promise.reject(fixtureErr)), fixtureErr.message);
});
test('calls `.cancel()` on promise when it exists', async t => {
const p = new PCancelable(onCancel => {
onCancel(() => {
t.pass();
});
return delay(200);
});
await t.throws(m(p, 50), m.TimeoutError);
t.true(p.canceled);
});