Javascript承诺不会等待解决
我认为我对承诺有一个相当好的理解,直到我遇到了一个简单的代码片段问题。我的印象是console.log调用将输出Javascript承诺不会等待解决,javascript,promise,Javascript,Promise,我认为我对承诺有一个相当好的理解,直到我遇到了一个简单的代码片段问题。我的印象是console.log调用将输出first second third,但结果却是second third first 有人能解释为什么第二个和第三个承诺能够在不等待第一个承诺的情况下继续下去吗 var Q = require('q'); (function() { var Obj = function() { function first() { var deferred = Q.def
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
这就成功了。我调用这些函数的原因是,在实际代码中,我需要将params传递给promise方法,这里省略了这些方法。看起来我必须用一个附加函数来包装它。谢谢你的帮助