简体   繁体   中英

Javascript promise - resolve (or) reject happening implicitly

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.

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.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM