简体   繁体   English

为 Promise.all 创建一个 promise 数组

[英]create an array of promises for Promise.all

I have an array of file paths, and I want to read all files inside Promise.all, and then perform some tasks.我有一个文件路径数组,我想读取 Promise.all 中的所有文件,然后执行一些任务。

var files = ["./file1.txt", "./file2.txt"]

Promise.all(files.forEach(file=>{ /* read file content */}))

You want to use Array.map :你想使用Array.map

var files = ["./file1.txt", "./file2.txt"]

Promise.all(files.map(async file=>{ /* read file content */}))

If you don't want it to be an async function but want it to return a promise, that's fine too如果你不希望它是一个异步函数但希望它返回一个承诺,那也没关系

var files = ["./file1.txt", "./file2.txt"]

Promise.all(files.map(file=>{ /* read file content, return a promise */}))

[edit] here's an example using my preferred file interface, fse - its' just fs but with promises: [编辑] 这是一个使用我喜欢的文件界面 fse 的例子——它只是 fs 但有承诺:

var files = ["./file1.txt", "./file2.txt"]

Promise.all(files.map(file=>{ 
    return fse.readFile(file, 'utf-8');
})).then(results => {
    // results is an array of strings of the contents of each file
})

https://www.npmjs.com/package/fs-extra https://www.npmjs.com/package/fs-extra

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM