I'm using ES6 promises, the idea of this function is to loop over an array of links, and for each link look for an image and stop once an image found.
In this case of the function that I wrote, the fastest promise resolves and others keeps executing, so what I want is to stop the execution of the remaining promises as soon as the first one resolves.
scrapImage(links) {
let promises = links.map((l) => getImageUrlAsync(l));
return Promise.race(promises);
}
Promises don't "execute". They're return values, not functions. A promise is not a control-surface to whatever function returns one. Sounds like you want to cancel getImageUrlAsync()
, so I would look for a cancellation API in whatever that API is.
Absent such a cancellation API, the best you can do is Promise.race
on the array of promises, as you're doing. As others have pointed out, when things run in parallel, it may already be too late to recall the other launched actions.
I would say it's no way to stop execution 'cause all promises start at the same time when use Promise.race.
Try to use loop, eg while.
Some sample code using ES7, if you are using babel.
async doSomething(links) {
let l = links.length;
while (l--) {
let res = await getImageUrlAsync(links[l]);
if (res) {
break;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With