jwkoo
jwkoo

Reputation: 2653

two weird behavior of Promise

I found myself lack of understanding with ES6 Promise.

I have two questions

Question 1)

// clear

var _o = null

var m = () => {
    return new Promise(k => {
        _o = k
    })
}

m().then(r => {console.log(r+1000)})

_o(100)

// 1100

As you've seen above, when _o is called with its value, promise resolves, and we can log the value (thanks to .then)

So the above example looks very clear.

But here is an example that I cannot fully understand.

// weird 

var _o = null

var test = () => {
    return new Promise(res => {
        _o = res
    })
}

test();

var p = _o(100)

console.log(p) // undefined

How can p be undefined?

According to the promise mdn documentation,

The Promise.resolve() method returns a Promise object that is resolved with a given value.

I thought that p has to be resolved Promise object.

Question 2)

Promise.resolve(10).then(r => console.log(r))  // 10


var p = Promise.resolve

p(10).then(r => console.log(r))

// Uncaught TypeError: PromiseResolve called on non-object

why does that p(10) fires an error?

I already referenced this article, but still failed to fully understand.

Thanks in advance for your help!

Upvotes: 1

Views: 76

Answers (1)

Felix Kling
Felix Kling

Reputation: 816700

How can p be undefined?

You seem to make the assumption that Promise.resolve (which you quote) is the same as the function that gets passed into the Promise constructor callback. They are not the same:

new Promise(resolve => {
   console.log(Promise.resolve === resolve);
})

In fact, the specification defines that the passed in function returns undefined: 25.6.1.3.2 Promise Resolve Functions.

You can think of Promise.resolve being equivalent to

Promise.resolve = function (value) {
  return new Promise(resolve => resolve(value));
}

why does that p(10) fires an error?

This is only partly related to Promise. It generally is due how this inside functions work. From the specification about Promise.resolve:

The resolve function expects its this value to be a constructor function that supports the parameter conventions of the Promise constructor.

If you call the function as p(...) then this is undefined.

If the function is called as Promise.resolve(...) then its this value will refer to Promise.

It's not uncommon for builtin functions to expect their this value to be a specific kind of object/value.

Upvotes: 2

Related Questions