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

How to Resolve JavaScript Promises Sequentially?

Linda Hamilton
Linda HamiltonOriginal
2024-12-13 17:49:15930browse

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

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

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

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

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

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

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!

Statement:
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