Home > Web Front-end > JS Tutorial > How to Resolve JavaScript Promises Sequentially?

How to Resolve JavaScript Promises Sequentially?

Linda Hamilton
Release: 2024-12-13 17:49:15
Original
953 people have browsed it

How to Resolve JavaScript Promises Sequentially?

​​​​​​​Resolve Promises Sequentially

Promises are a common way to handle asynchronous operations in JavaScript. However, it can be challenging to control the order in which promises are resolved.

The Problem:

Consider the following code that reads a series of files serially:

var readFile = function(file) {
  ... // Returns a promise.
};

var readFiles = function(files) {
  return new Promise((resolve, reject) => {
    var readSequential = function(index) {
      if (index >= files.length) {
        resolve();
      } else {
        readFile(files[index]).then(function() {
          readSequential(index + 1);
        }).catch(reject);
      }
    };

    readSequential(0); // Start with the first file!
  });
};
Copy after login

This code uses recursion to read the files one after another, but it can be challenging to work with.

Avoid Recursion with Async/Await:

In modern JavaScript, using async functions and await is a more elegant solution:

async function readFiles(files) {
  for(const file of files) {
    await readFile(file);
  }
};
Copy after login

Alternatively, Use Iterators:

Async generators provide an alternative approach to reading files sequentially:

async function* readFiles(files) {
  for(const file of files) {
    yield await readFile(file);
  }
};
Copy after login

Consider a Simple Loop:

If you prefer a simpler approach, a basic for loop can suffice:

var readFiles = function(files) {
  var p = Promise.resolve(); // Q() in q

  files.forEach(file =>
      p = p.then(() => readFile(file)); 
  );
  return p;
};
Copy after login

Or, Utilize Promise Reduction:

A more compact solution using reduce:

var readFiles = function(files) {
  return files.reduce((p, file) => {
     return p.then(() => readFile(file));
  }, Promise.resolve()); // initial
};
Copy after login

Library Utility Methods

Certain promise libraries (e.g., Bluebird) provide utility methods tailored for this purpose:

var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs"));

var readAll = Promise.resolve(files).map(fs.readFileAsync,{concurrency: 1 });
// if the order matters, you can use Promise.each instead and omit concurrency param

readAll.then(function(allFileContents){
    // do stuff to read files.
});
Copy after login

The above is the detailed content of How to Resolve JavaScript Promises Sequentially?. 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