所有
我很擅长承诺,我想做的是:
[1]下载文件A,当A下载,然后下载文件B,B准备好后,再下载加载C.
[2]创建一个下载文件A的功能,无论它被调用了多少次,它只下载文件一次。
[1]和[2]不是相关的任务。你可以用其中一个或两个来帮助我。
有人能给我一个有希望的简单例子吗?感谢。
答案 0 :(得分:1)
在node.js中使用Bluebird promise库,这里有三种方法:
// load and promisify modules
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require('fs'));
Purely Sequential,每个步骤单独编码
// 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
});