Reputation:
From chrome console, i am using native JS promises and it is getting resolved automatically,
var p = new Promise(
function(resolve, reject){
resolve(200)
})
returns
undefined
p.then(function(response){
console.log(response)
})
returns
200
I think, Promise.then is meant for registering resolve (or) reject callbacks. But, why is it triggering resolve callback function itself in this case.
Upvotes: 0
Views: 1185
Reputation: 276266
Why is it logging undefined?
Because a var
statement has not useful return value. For example if you type var x = 5
your console will log undefined
.
Why is it resolving?
Because you called resolve
which is how you resolve a promise in the promise constructor.
var p = new Promise(function(resolve, reject){
resolve(200)
});
Is basically the same as var p = Promise.resolve(200)
. This isn't only explicitly resolving it - it's the only way to resolve it. If you want to not resolve it remove that resolve(200)
line.
But, why is it triggering resolve callback function itself in this case.
It is not, if you console.log(p)
and remove the then
part it will log a resolved promise.
Upvotes: 3
Reputation: 9466
Here, How & when does the resolve promise trigger happen?
The then
callback is executed in some future next turn of the event loop, if it is attached before the promise resolves. If it is attached after it has resolved, it will execute in the next turn, as if it was wrapped in a setTimeout(function () {}, 0)
call.
atleast in my 2 lines of code, i am not resolving it explicitly?
When you call resolve
, yes, you are resolving the promise.
Upvotes: 1