【发布时间】:2016-08-10 02:45:11
【问题描述】:
我正在尝试执行一系列承诺。 我已经阅读了 q kriskowal 的 github 页面和他的序列示例,但他从未将之前的结果用于下一个 promise。
return foo(initialVal).then(bar).then(baz).then(qux);
所以我的代码是:
var Q = require('Q');
function foo(arg) {
console.log('foo arg=' + arg);
var d = Q.defer();
bar(arg+1)
.then(function(){
d.resolve(arg);
}, function(error){
d.reject(error);
})
return d.promise;
}
function bar(arg) {
console.log('bar arg=' + arg);
var d = Q.defer();
d.resolve(arg);
return d.promise;
}
function test() {
var defer = Q.defer();
foo('a')
.then(function (success) {
var def1 = Q.defer();
console.dir('success: ' + success);
bar('test');
})
.then(function (rest) {
return foo('b')
})
.then(function(success){
defer.resolve(success);
}, function(error){
defer.reject(error);
});
return defer.promise;
}
var b = [test(), test(),test()];
Q.all(b)
.then(function(result){
console.dir(result);
})
输出是:
foo arg=a
bar arg=a1
foo arg=a
bar arg=a1
foo arg=a
bar arg=a1
'success: a'
bar arg=test
'success: a'
bar arg=test
'success: a'
bar arg=test
foo arg=b
bar arg=b1
foo arg=b
bar arg=b1
foo arg=b
bar arg=b1
[ 'b', 'b', 'b' ]
我想要的是:
foo arg=a
bar arg=a1
'success: a'
bar arg=test
foo arg=b
bar arg=b1
foo arg=a
bar arg=a1
'success: a'
bar arg=test
foo arg=b
bar arg=b1
foo arg=a
bar arg=a1
'success: a'
bar arg=test
foo arg=b
bar arg=b1
【问题讨论】: