Search code examples
javascriptpromisees6-promisecancellation

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);
}

Solution

  • 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.