Run all promises in parallel using Promise.all() but get response of each promise as it resolves and do processing on that.
Is there a work around like I can attach a callback to promises.resolve
that as a certain promise resolves it calls a callback
Example
let p1 = Promise.resolve(1)
let p2 = Promise.resolve(2)
let p3 = Promise.resolve(3)
Promise.all([p1,p2,p3])
function processData(data)
{
....
}
I want to run all of them in parallel but don't want to wait till all of them get resolved but instead call processData()
as soon as a promise resolves for each of them.
Iterate over the promises with forEach
instead, attaching processData
to each in a .then
:
const processData = console.log; let p1 = Promise.resolve(1); let p2 = Promise.resolve(2); let p3 = Promise.resolve(3); [p1, p2, p3].forEach(prom => prom .then(processData) .catch((err) => { /* handle errors */ }) );
You can attach a .then
after resolving and assign processData as a callback.
let p1 = Promise.resolve(1).then(processData);
let p2 = Promise.resolve(1).then(processData);
let p3 = Promise.resolve(1).then(processData);
Promise.all([p1,p2,p3])
Just don't use Promise.all()
:
let p1 = Promise.resolve(1).then(processData);
let p2 = Promise.resolve(2).then(processData);
let p3 = Promise.resolve(3).then(processData);
If you need to call processData
as soon as a promise resolves but want to wait for all promises to resolve before continuing then use Promise.all()
only for the wait but call processData
inside each promise's .then()
:
(async () {
let p1 = Promise.resolve(1).then(processData);
let p2 = Promise.resolve(2).then(processData);
let p3 = Promise.resolve(3).then(processData);
await Promise.all([p1,p2,p3]);
// continue processing..
})();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.