Created
July 28, 2018 04:13
-
-
Save johnsonjo4531/d64a529bb23b755007f9bb650e7768b4 to your computer and use it in GitHub Desktop.
Useful promisified timeout with cancellation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports.timeout = function timeout(ms, clear = () => {}) { | |
return new Promise((res, rej) => { | |
var t = setTimeout(res, ms); | |
clear(function cancel () { | |
clearTimeout(t); | |
rej("CANCELLED BY TIMEOUT"); | |
}); | |
}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var { timeout } = require("./timeout"); | |
// scenario 1: regular timeout | |
(async () => { | |
await timeout(1000); | |
console.log("scenario 1 done"); | |
})(); | |
// scenario 2: cancellation | |
(async () => { | |
let passed = true; | |
try { | |
await timeout(1000, async function(cancel) { | |
await timeout(500); | |
cancel(); | |
}); | |
passed = false; | |
} catch (err) { | |
// ignore error | |
} | |
if (passed) { | |
console.log("scenario 2 passed"); | |
} else { | |
console.log("scenario 2 failed"); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment