Home >Web Front-end >JS Tutorial >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; };
With reduce:
var readFiles = function(files) { return files.reduce((p, file) => { return p.then(() => readFile(file)); }, Promise.resolve()); // initial };
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 });
In modern JavaScript, async functions can also be used for sequential promises:
async function readFiles(files) { for(const file of files) { await readFile(file); } };
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!