Home >Web Front-end >JS Tutorial >How Can I Sequentially Resolve Promises for File Reading?
Problem:
Consider the code below that serially reads an array of files.
var readFile = function(file) {...}; var readFiles = function(files) {...};
While this recursive solution works, a simpler method is desired without using the readSequential function.
Solution 1: Promise.all
Originally, Promise.all was attempted, but it concurrently invoked all readFile calls.
var readFiles = function(files) {...};
Solution 2: Async Functions
If supported by the environment, an async function can be used.
async function readFiles(files) {...};
Solution 3: Async Generator
For deferred reading, an async generator can be used.
async function* readFiles(files) {...};
Solution 4: For Loop
A simple for loop can be used instead.
var readFiles = function(files) {...};
Solution 5: Reduce
Alternatively, a compact solution using reduce is possible.
var readFiles = function(files) {...};
Solution 6: Promise Libraries
Promise libraries like Bluebird offer utility methods for this purpose.
var Promise = require("bluebird"); var readFileAll = Promise.resolve(files).map(fs.readFileAsync,{concurrency: 1 });
The above is the detailed content of How Can I Sequentially Resolve Promises for File Reading?. For more information, please follow other related articles on the PHP Chinese website!