Skip to content

Instantly share code, notes, and snippets.

@nnnikolay
Last active November 16, 2017 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nnnikolay/1cb504b5687d091d443f9cf95791e5e1 to your computer and use it in GitHub Desktop.
Save nnnikolay/1cb504b5687d091d443f9cf95791e5e1 to your computer and use it in GitHub Desktop.
Couple of advanced techniques to work with JS promises

Someimtes it can be usefull to do banch of tasks in "parallel" and do not stop if some of them has been finished with the error

Promise.all([
  Promise.resolve(33).then((d) => { throw new Error(d)} ).catch(e => console.error('Inside ' + e)),
  Promise.resolve('test')
]).then(result => console.log(result)).catch(e => console.error(e));

In the output we will see

> Inside Error: 33
[ undefined, 'test' ]

Although one of promises returned the error, others kept working.

Without handling the error right there in the first Promise we would end up with the following picture:

Error: Error: 33
    at Promise.all.Promise.resolve.then (repl:2:41)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:228:7)

And we would never catch into latest .then() because Promise.all waits for all fulfillments (or the first rejection).

Another advanced approach which I've used for fetching the web pages even though some of the requests could return timeout as a respone was the following:

const fetch = (url) => {
  return node-fetch(url)
    .then(result => result.json())
    .catch((e) => {
      return new Promise((resolve) => setTimeout(() => resolve(fetch(url)), timeout));
    });
};

tasks = [fetch(url1), fetch(url2) ....];

Promise.all(tasks).then(......)

Here we use the same approach as above but in catch we return another promise which we're trying to resolve recursively calling fetch function within the time (setTimeout).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment