Home > Web Front-end > JS Tutorial > How to Execute a Sequence of Promises in Order and Handle Rejections?

How to Execute a Sequence of Promises in Order and Handle Rejections?

Susan Sarandon
Release: 2024-11-24 13:18:11
Original
1000 people have browsed it

How to Execute a Sequence of Promises in Order and Handle Rejections?

How to Synchronize a Sequence of Promises

In this scenario, you need to ensure that:

  • Promises are resolved in the same order they are listed in the array.
  • If any element is rejected, the entire sequence should reject.

While there is no direct built-in solution for this, here are ways to achieve this behavior:

Manual Iteration Using Recursion:

function sequence(arr) {
  const index = 0;

  function next() {
    if (index < arr.length) {
      arr[index]().then(next).catch(reject);
      index++;
    }
  }
  next();
}
Copy after login

Using Reduce:

function sequence(arr) {
  return arr.reduce((p, item) => {
    return p.then(() => item()); // Assuming each element is a promise-returning function
  }, Promise.resolve());
}
Copy after login

Using Promise.mapSeries:

If you're using the Bluebird Promise library, you can utilize its Promise.mapSeries method:

function sequence(arr) {
  return Promise.mapSeries(arr, item => item());
}
Copy after login

Using ES7 Async/Await:

If supported, you can use async/await to achieve this:

async function sequence(arr) {
  const results = [];
  for (let item of arr) {
    results.push(await item());
  }
  return results;
}
Copy after login

Using spex Library:

The spex library provides a sequence method that allows you to iterate over a sequence of dynamic promises:

import { sequence } from 'spex';

function sequence(nextPromise) {
  // while nextPromise() creates and returns another promise, continue resolving it;
}
Copy after login

Remember, if any element in the array is rejected, the sequence will reject as soon as that rejection is encountered. This behavior ensures that further elements are not processed.

The above is the detailed content of How to Execute a Sequence of Promises in Order and Handle Rejections?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template