chr*_*ris 5 javascript promise
我认为我对承诺有一个很好的理解,直到我遇到一个简化的代码片段问题.我的印象是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());
}());
Run Code Online (Sandbox Code Playgroud)
您不应该调用该函数,而是传递函数,就像这样
obj.first()
.then(obj.second)
.then(obj.third);
Run Code Online (Sandbox Code Playgroud)
产量
in the first
in the second
in the third
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2800 次 |
| 最近记录: |