I have this piece of code:
var myArray = [1, 2, 3, 4, 5, 6]
function myPromise(num){
return new Promise(res => {
setTimeout(()=>{
res( console.log("done: " + num) )
}, 2000);
console.log("Getting here???" + num);
});
}
myPromise(myArray[0]).then(x =>
console.log("what value: " + x));
I am really confused as to why the console.log(“what value: ” + x) print x as undefined.
I have read an example here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#return_value especially the one it says under “Chaining”.
In that piece of code, the asynchornicity of “then” is demonstrated clearly I think because I can see that the console.log or something inside then “later then” get executed before the “then that comes before it”. So we were able to see the order of print out in the console like this:
// Last Then: oops... didn't bother to instantiate and return a promise in the prior then so the sequence may be a bit surprising
// foobar
// foobarbaz
but how comes in my code above, even thought the (“what value: ” + x) actually executed after the promise in front of it, it still gets an undefined for the variable x?
enter image description here
On the other hand, the code in the example from the javascript site is able to have those “later then” getting the string value passed from those “then” or “promise” before it?
but my code here is not able to get the x value coming from the promise that comes before it? (I am confused because the printout seems to suggests the code inside the then get executed after myPromise’s promise resolve. But x being undefined seems indicating something I don’t understand.
Could someone explains why x is undefined?
thanks a lot
I have read example from the mozilla site, and also example from here How to execute promises sequentially, passing the parameters from an array?
but that example seem not quite similar to what I have here.
1
The console.log()
has no return value. You are resolving the console.log()
, which returns undefined
. You should resolve the num
itself:
let myArray = [1, 2, 3, 4, 5, 6];
function myPromise(num) {
return new Promise(res => {
setTimeout(() => {
console.log('done: ' + num);
res(num);
}, 2000);
console.log('Getting here???' + num);
});
}
myPromise(myArray[0]).then(x =>
console.log('what value: ' + x));