-
-
Save joepie91/2664c85a744e6bd0629c to your computer and use it in GitHub Desktop.
| module.exports = function(duration) { | |
| return function(){ | |
| return new Promise(function(resolve, reject){ | |
| setTimeout(function(){ | |
| resolve(); | |
| }, duration) | |
| }); | |
| }; | |
| }; | |
| // Usage: | |
| var delayPromise = require("./delay-promise"); | |
| doThing() | |
| .then(...) | |
| .then(delayPromise(5000)) | |
| .then(...) |
Hi @berstend - I don't think util.promisify does what you hoped.
It expects a function whose callback argument is last. setTimeout's callback method is first, and timeout in milliseconds is 2nd. (The rarely used context arg is 3rd.)
This necessitates a wrapper function, I use something similar to https://gist.github.com/joepie91/2664c85a744e6bd0629c#gistcomment-2555399 :
const delay = ms => new Promise(yea => setTimeout(yea, ms));
delay(1000)
.then(() => console.log('waited 1000 secs'))Hello future self, here's the TypeScript version for your copy/pasting pleasure:
const delay = (ms: number) => new Promise(_ => setTimeout(_, ms))and my favorite JS version:
const delay = ms => new Promise(_ => setTimeout(_, ms))You forget to clear the setTimeout
const delay = async <T>(timeout: number, value?: T) => {
return new Promise((resolve) => {
const timeoutId = setTimeout(() => {
resolve(value);
clearTimeout(timeoutId);
}, timeout);
});
};
@tolotrasmile That shouldn't be necessary, since this is a setTimeout, not a setInterval. A setTimeout only ever fires once, so once you're in the callback, there is nothing to clearTimeout anymore.
clearTimeout is basically just for cancelling a setTimeout that has not yet occurred.
For nodeJS only
import { setTimeout } from "timers/promises";
await setTimeout(3000, value);
As I find myself ending up on this very page approx. once a week (copy pasting @PabloCorso version), here's a Node.js specific alternative for my future self 😄