如何获得仅在连接完成后才执行的 promise ?
var fs = require('fs');
var testFolder = './lib/';
var files = ['hello.txt', 'goodbye.txt'];
var contents = '';
//creating array of promises
let promises = files.map(async e => {
return await fs.readFile(testFolder + e, "utf8", function (err, content) {
contents += content + ".\n";
});
}
);
console.log(promises);
//this should happen last but "contents" is still empty string?
Promise.all(promises).then(()=> console.log(contents));
最佳答案
fs.readFile
不返回 promise 。
你应该使用 util.promisify
让它这样做。
此外,正如 Patrick Hübl-Neschkudla 在下面的评论中提到的,没有必要使用 async
/await
因为 readFile
已经返回现在是一个 promise ,我们要等到以后才处理结果。
Bergi 还在评论中指出,fs.readFile
回调不能保证按创建顺序返回。事实上,大多数 fs
操作都是这种情况,因为其他进程总是可以通过同时操作文件来干扰您的进程 - 例如,如果有人写入您将要读取的文件怎么办?。
您应该在所有读取完成后执行串联,而不是在它们发生时执行(因为它们可能会不同步)。
这也将确保 all rejections are properly caught无论哪个 promise (文件读取)失败。
const readFile = util.promisify(fs.readFile);
Promise.all(
files.map(e => readFile(testFolder + e, "utf8"))
)
.then(contentArray => contentArray.join('.\n'))
.then(console.log);
关于javascript - 准备就绪时执行一系列 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47310897/