Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop promises execution once the first promise resolves

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);
}
like image 890
zianwar Avatar asked Mar 14 '16 15:03

zianwar


2 Answers

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.

like image 178
jib Avatar answered Sep 28 '22 02:09

jib


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;
    }
  }
}
like image 30
Ivan Nosov Avatar answered Sep 28 '22 01:09

Ivan Nosov