【发布时间】:2017-05-28 15:32:12
【问题描述】:
我正在尝试在一个承诺中做一个 for 循环,但不幸的是,它的输出不是我所期望的:
我的代码
var ahaha = function mytestfunction(numb){
return new Promise(function(resolve, reject) {
console.log(numb);
return resolve('test');
})
.then(function(x) {
z='firststep' + x ;
console.log(z);
return z;
})
.then(function(z) {
console.log(z + 'secondstep');
return z
})
.then(function(z) {
console.log(z + 'thirdstep')
});
};
var promises = [];
for (var i = 1; i <= 2; i++) {
promises.push(ahaha(i));
}
Promise.all(promises)
.then(function(data){ console.log("everything is finished")});
它返回的是:
1
2
firststeptest
firststeptest
firststeptestsecondstep
firststeptestsecondstep
firststeptestthirdstep
firststeptestthirdstep
everything is finished
但我希望它返回
1
firststeptest
firststeptestsecondstep
firststeptestthirdstep
2
firststeptest
firststeptestsecondstep
firststeptestthirdstep
everything is finished
我不明白为什么承诺没有一个接一个地链接。
请注意,我使用 async.waterfall 成功执行了此操作,但我也想知道如何使用 promises 执行此操作。
非常感谢
【问题讨论】:
标签: node.js promise ecmascript-6