From 57a26e0277d2aab6a88193a44ffee78e360b57b1 Mon Sep 17 00:00:00 2001 From: Timur Shemsedinov Date: Mon, 22 Feb 2021 11:31:40 +0200 Subject: [PATCH] Implemented `await delay(msec, signal)` PR-URL: https://github.com/metarhia/metautil/pull/31 --- CHANGELOG.md | 1 + lib/utilities.js | 11 +++++++++++ test/{timeout.js => async.js} | 22 +++++++++++++++++++++- 3 files changed, 33 insertions(+), 1 deletion(-) rename test/{timeout.js => async.js} (50%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b42850..7416721 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## [Unreleased][unreleased] +- Implemented `await delay(msec, signal)` - Fix timeout behaviour to reject promise (throw) - Generate errors on timeout and on abort timeout diff --git a/lib/utilities.js b/lib/utilities.js index cf54376..f53ef6f 100644 --- a/lib/utilities.js +++ b/lib/utilities.js @@ -162,6 +162,16 @@ const timeout = (msec, signal = null) => }); }); +const delay = (msec, signal = null) => + new Promise((resolve, reject) => { + const timer = setTimeout(resolve, msec); + if (!signal) return; + signal.on('abort', () => { + clearTimeout(timer); + reject(new Error('Delay aborted')); + }); + }); + module.exports = { random, sample, @@ -179,4 +189,5 @@ module.exports = { parseCookies, createAbortController, timeout, + delay, }; diff --git a/test/timeout.js b/test/async.js similarity index 50% rename from test/timeout.js rename to test/async.js index 8ded1da..97047fd 100644 --- a/test/timeout.js +++ b/test/async.js @@ -1,7 +1,7 @@ 'use strict'; const metatests = require('metatests'); -const { timeout, createAbortController } = require('..'); +const { timeout, delay, createAbortController } = require('..'); metatests.test('Abortable timeout', async (test) => { try { @@ -22,3 +22,23 @@ metatests.test('Abortable timeout', async (test) => { test.end(); } }); + +metatests.test('Abortable delay', async (test) => { + try { + const res = await delay(10); + test.strictSame(res, undefined); + } catch (err) { + test.error(new Error('Should not be executed')); + } + const ac = createAbortController(); + setTimeout(() => { + ac.abort(); + }, 10); + try { + await delay(100, ac.signal); + test.error(new Error('Should not be executed')); + } catch (err) { + test.strictSame(err.message, 'Delay aborted'); + test.end(); + } +});