How to setTimeout on async await call node
Actually, I have a pretty standard chunk of code that I use to do that:
function PromiseTimeout(delayms) {
return new Promise(function (resolve, reject) {
setTimeout(resolve, delayms);
});
}
Usage:
await PromiseTimeout(1000);
If you're using Bluebird promises, then it's built in as Promise.timeout
.
More to your problem: Have you checked API docs? Some APIs tell you how much you have to wait before next request. Or allow downloading data in larger bulk.
You can use a simple little function that returns a promise that resolves after a delay:
function delay(t, val) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve(val);
}, t);
});
}
And, then await
that inside your loop:
exports.getProducts = async (req, res) => {
let request;
for (let id of productids) {
request = await getProduct(id);
await delay(5000);
}
};
Note: I also switched your for
loop to use for/of
which is not required, but is a bit cleaner than what you had.
Or, in modern versions of nodejs, you can use timersPromises.setTimeout()
which is a built-in timer that returns a promise (as of nodejs v15):
const setTimeoutP = require('timers/promises').setTimeout;
exports.getProducts = async (req, res) => {
let request;
for (let id of productids) {
request = await getProduct(id);
await setTimeoutP(5000);
}
};