Cra*_*hax 7 javascript node.js promise ecmascript-6 bluebird
我写了以下node.js文件:
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);
});
})
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我用Promise.all
它来等待读取csv文件的两个操作.我不明白为什么,但是当我运行代码时,该行'console.log(result)'
未提交.
我的第二个问题是我希望回调函数Promise.all.then()
接受两个不同的变量,而其中每个变量都是相关承诺的结果.
nem*_*035 23
第一个问题
Promise.all
采取一系列承诺
更改:
Promise.all(read_csv_file("devices.csv"), read_csv_file("bugs.csv"))
Run Code Online (Sandbox Code Playgroud)
to(添加[]
参数)
Promise.all([read_csv_file("devices.csv"), read_csv_file("bugs.csv")])
// ---------^-------------------------------------------------------^
Run Code Online (Sandbox Code Playgroud)
第二个问题
在Promise.all
与结果为每个传递给它的承诺数组缓解.
这意味着您可以将结果提取为变量,如:
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
});
Run Code Online (Sandbox Code Playgroud)
您可以使用ES6 + 解构来进一步简化代码:
Promise.all([read_csv_file("devices.csv"), read_csv_file("bugs.csv")])
.then(function([first, second]) {
});
Run Code Online (Sandbox Code Playgroud)