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!