Skip to content

Commit

Permalink
Implemented await delay(msec, signal)
Browse files Browse the repository at this point in the history
PR-URL: #31
  • Loading branch information
tshemsedinov committed Feb 22, 2021
1 parent fed9dc4 commit 57a26e0
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
11 changes: 11 additions & 0 deletions lib/utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -179,4 +189,5 @@ module.exports = {
parseCookies,
createAbortController,
timeout,
delay,
};
22 changes: 21 additions & 1 deletion test/timeout.js → test/async.js
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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();
}
});

0 comments on commit 57a26e0

Please sign in to comment.