[英]Javascript promises not waiting for resolve
我认为我对承诺有一个很好的理解,直到我遇到一个简化的代码片段问题。 我的印象是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());
}());
您不应该调用该函数,而是传递函数,就像这样
obj.first()
.then(obj.second)
.then(obj.third);
产量
in the first
in the second
in the third
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.