From 032432734238d696bb88aeb4a6fc5d4ffc454b17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kevin=20M=C3=A5rtensson?= Date: Sun, 19 Nov 2017 10:33:44 +0100 Subject: [PATCH] Cancel any cancelable input promises (#3) --- index.js | 4 ++++ package.json | 1 + test.js | 14 ++++++++++++++ 3 files changed, 19 insertions(+) diff --git a/index.js b/index.js index fa48cc7..ab2d294 100644 --- a/index.js +++ b/index.js @@ -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); diff --git a/package.json b/package.json index a227735..ae678ab 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ "devDependencies": { "ava": "*", "delay": "^2.0.0", + "p-cancelable": "^0.3.0", "xo": "*" } } diff --git a/test.js b/test.js index 68f3da3..8aa3879 100644 --- a/test.js +++ b/test.js @@ -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); +});