我认为我对承诺有一个很好的理解,直到我遇到一个简化的代码片段问题。我的印象是console.log调用会输出first second third
,而是导致second third first
。
有人可以解释为什么第二和第三个承诺能够继续而不等待第一个承诺。
var Q = require('q');
(function() {
var Obj = function() {
function first() {
var deferred = Q.defer();
setTimeout(function() {
console.log('in the first')
deferred.resolve();
}, 200);
return deferred.promise;
}
function second() {
return Q.fcall(function() {
console.log('in the second');
})
}
function third() {
return Q.fcall(function() {
console.log('in the third');
})
}
return {
first: first,
second: second,
third: third
}
};
var obj = Obj();
obj.first()
.then(obj.second())
.then(obj.third());
}());
答案 0 :(得分:6)
您不应该调用该函数,而是传递函数,如此
obj.first()
.then(obj.second)
.then(obj.third);
<强>输出强>
in the first
in the second
in the third