Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Losing object reference in Javascript with await

I was learning the event loop of Js and tried to run this function:

async function foo() {
    console.log('FIrst');
    let a = await new Promise((resolve,reject)=>{
        console.log("inside Promise");
        resolve();
    })
    console.log(a);
    console.log('Second');
} 
foo();
console.log('Three');

On running this code gave output as follows:

FIrst
inside Promise
Three
undefined
Second

I am not able to understand why did a lose its value (the object assignment). I have searched for this behavior but was not able to understand from the answers.
Can someone please explain what is the order of execution which results in this output.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you await the newly created promise, you’re not assigning the promise to a, you’re assigning the resolve value of it.

async function foo() {
    let a = await new Promise((resolve, reject) => {
        // This is where the value stems from
        resolve(42);
    });
    console.log(a);
} 
foo();

If you want to keep the await while also retrieving the reference, you can separate those two steps:

async function foo() {
    let a = new Promise((resolve, reject) => {
        resolve(42);
    });
    await a;
    console.log(a instanceof Promise);
} 
foo();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading