I have eg: 20 (can be dynamic) promises which makes API call. I am dividing into batches of 10. like [[p1,... p10], [p11,... p20] ...]
I am having for loop on it and executing p1 to p10 promises using promise.all
like that then p11 to p20 etc..
let res: any = [];
batch.forEach(item => {
Promise.all(item).then(values => {
res = [...res, ...values];
});
})
Now Here I want to add delay between p1..p10
to p11..p20
. What is the way for this in Javascript ?
CodePudding user response:
async function timeOut(delay) {
return new Promise(resolve => setTimeout(() => resolve(true), delay))
}
async function wrapper() {
let res: any = [];
for(let item of batch) {
const values = await Promise.all(item)
res.push(...values);
await timeOut(2000)
}
}
wrapper()
CodePudding user response:
Inside a Array.forEach method you can't await
promises so the best approach is to use a common for...of
loop.
Here i declared a sleep function to implement the delay and then i just wrote your logic but using a normal loop
const sleep = async sec => new Promise((resolve, _reject) => setTimeout(resolve, sec * 1000))
;(async () => {
let res: any = [];
for(const item of batch) {
const values = await Promise.all(item);
res.push(...values)
await sleep(2) // n of seconds you want
}
})()
CodePudding user response:
If you want a serial execution with wait
, you can follow below using reduce
with serial promise chaining.
const wait = (timer) => new Promise((resolve) => setTimeout(resolve, timer * 1000));
let res: any = [];
batch.reduce((acc, item) => {
// chain last item promise in loop
return acc.then(() =>
Promise.all(item).then(values => {
res = [...res, ...values];
})
// one items promise resolved wait 10sec
.then(() => wait(10))
);
}, Promise.resolve());