Javascript承诺不会等待解决
问题描述:
我认为我对承诺有一个体面的理解,直到我遇到了一个简化的代码段下面的问题。我的印象是,console.log调用会输出first second third
,但取而代之的是second third first
。Javascript承诺不会等待解决
有人可以解释为什么第二个和第三个承诺能够继续,而不等待第一个承诺。
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
该诀窍。我之所以调用函数的原因是,在实际的代码中,我需要将参数传递给承诺方法,这些方法在此处被遗漏。它看起来像我将不得不包装在一个额外的功能。谢谢您的帮助 – chris