Home > Web Front-end > JS Tutorial > How Can I Resolve Promises Sequentially in JavaScript?

How Can I Resolve Promises Sequentially in JavaScript?

Barbara Streisand
Release: 2024-12-15 07:37:09
Original
672 people have browsed it

How Can I Resolve Promises Sequentially in JavaScript?

Resolve Promises Sequentially

This article explores ways to address the problem of resolving promises in a sequential manner.

The provided code snippet uses recursion to read an array of files serially, resolving the promise only after all files have been read. While this approach is functional, it introduces unnecessary recursion.

A simpler alternative is to leverage a for loop or reduce to chain the promise resolutions:

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

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

With reduce:

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

Promise libraries often provide utility methods for sequential resolution, such as Bluebird's map() with concurrency: 1:

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

var readAll = Promise.resolve(files).map(fs.readFileAsync,{concurrency: 1 });
Copy after login

In modern JavaScript, async functions can also be used for sequential promises:

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

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