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());
}());
The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or a JavaScript module.
You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.
The keyword await is used to wait for a Promise. It can only be used inside an async function. This keyword makes JavaScript wait until that promise settles and returns its result.
A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With