在 node.js 中使用 Bluebird Promise 库,这里有三种方法:
// load and promisify modules
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require('fs'));
纯顺序,每一步单独编码
// purely sequential
fs.readFileAsync("file1").then(function(file1) {
// file1 contents here
return fs.readFileAsync("file2");
}).then(function(file2) {
// file2 contents here
return fs.readFileAsync("file3");
}).then(function(file3) {
// file3 contents here
}).catch(function(err) {
// error here
});
并行读取,完成后收集结果
// read all at once, collect results at end
Promise.map(["file1", "file2", "file3"], function(filename) {
return fs.readFileAsync(filename);
}).then(function(files) {
// access the files array here with all the file contents in it
// files[0], files[1], files[2]
}).catch(function(err) {
// error here
});
从数组中顺序读取
// sequential from an array
Promise.map(["file1", "file2", "file3"], function(filename) {
return fs.readFileAsync(filename);
}, {concurrency: 1}).then(function(files) {
// access the files array here with all the file contents in it
// files[0], files[1], files[2]
}).catch(function(err) {
// error here
});