I thought I had a decent understanding of promises, until I ran into a problem with a simplifed code snippet bellow. I was under the impression that the console.log calls would output first second third
, but instead results in second third first
.
Can someone explain why the second and third promises are able to continue on without waiting for the 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());
}());
You shouldn't be invoking the function, but pass the function, like this
obj.first()
.then(obj.second)
.then(obj.third);
Output
in the first
in the second
in the third
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.