Update 2017 : I would use an async function if the environment supports it:
(2017年更新 :如果环境支持,我将使用异步功能:)
async function readFiles(files) {
for(const file of files) {
await readFile(file);
}
};
If you'd like, you can defer reading the files until you need them using an async generator (if your environment supports it):
(如果需要,可以使用异步生成器(如果您的环境支持)将读取文件的时间推迟到需要它们之前:)
async function* readFiles(files) {
for(const file of files) {
yield await readFile(file);
}
};
Update: In second thought - I might use a for loop instead:
(更新:再次考虑-我可能会使用for循环:)
var readFiles = function(files) {
var p = Promise.resolve(); // Q() in q
files.forEach(file =>
p = p.then(() => readFile(file));
);
return p;
};
Or more compactly, with reduce:
(或更紧凑地使用减少:)
var readFiles = function(files) {
return files.reduce((p, file) => {
return p.then(() => readFile(file));
}, Promise.resolve()); // initial
};
In other promise libraries (like when and Bluebird) you have utility methods for this.
(在其他Promise库(如when和Bluebird)中,您可以使用此方法。)
For example, Bluebird would be:
(例如,蓝鸟将是:)
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.
});
Although there is really no reason not to use async await today.
(尽管今天确实没有理由不使用异步等待。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…