JavaScript 中的 Promise.all:如何获取所有 Promise 的解析值? [英] Promise.all in JavaScript: How to get resolve value for all promises?
问题描述
我编写了以下 node.js 文件:
I wrote the following node.js file:
var csv = require('csv-parser');
var fs = require('fs')
var Promise = require('bluebird');
var filename = "devices.csv";
var devices;
Promise.all(read_csv_file("devices.csv"), read_csv_file("bugs.csv")).then(function(result) {
console.log(result);
});
function read_csv_file(filename) {
return new Promise(function (resolve, reject) {
var result = []
fs.createReadStream(filename)
.pipe(csv())
.on('data', function (data) {
result.push(data)
}).on('end', function () {
resolve(result);
});
})
}
如您所见,我使用 Promise.all
来等待读取 csv 文件的两个操作.我不明白为什么,但是当我运行代码时,行 'console.log(result)'
没有提交.
As you can see, I use Promise.all
in order to wait for both operations of reading the csv files. I don't understand why but when I run the code the line 'console.log(result)'
is not committed.
我的第二个问题是我希望 Promise.all.then()
的回调函数接受两个不同的变量,而每个变量都是相关承诺的结果.
My second question is I want that the callback function of Promise.all.then()
accepts two different variables, while each one of them is the result of the relevant promise.
推荐答案
第一个问题
Promise.all
接受一组承诺
变化:
Promise.all(read_csv_file("devices.csv"), read_csv_file("bugs.csv"))
to(在参数周围添加[]
)
to (add []
around arguments)
Promise.all([read_csv_file("devices.csv"), read_csv_file("bugs.csv")])
// ---------^-------------------------------------------------------^
第二个问题
Promise.all
解析为您传递给它的每个承诺的结果数组.
The Promise.all
resolves with an array of results for each of the promises you passed into it.
这意味着您可以将结果提取到变量中,例如:
This means you can extract the results into variables like:
Promise.all([read_csv_file("devices.csv"), read_csv_file("bugs.csv")])
.then(function(results) {
var first = results[0]; // contents of the first csv file
var second = results[1]; // contents of the second csv file
});
您可以使用 ES6+ 解构进一步简化代码:
You can use ES6+ destructuring to further simplify the code:
Promise.all([read_csv_file("devices.csv"), read_csv_file("bugs.csv")])
.then(function([first, second]) {
});
这篇关于JavaScript 中的 Promise.all:如何获取所有 Promise 的解析值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!