JavaScript中的Promise.all:如何获得所有承诺的解析价值? [英] 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 + destructuring 以进一步简化代码:
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:如何获得所有承诺的解析价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!