Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
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.

about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

This is because if you are using await it returns to a variable the thing that you've passed in resolve, so you didn't pass any value in resole this is why it is undefined

about 4 years ago · Santiago Gelvez Relatório

0

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();

about 4 years ago · Santiago Gelvez Relatório

0

The reason why the promise's value is undefined is because you did not set the value that the promise should output. If you want the promise to return something other than undefined, place an expression or string inside the resolve() function. If you want the promise to return "Promise completed" after it resolves and console.log the result, simply use the code

async function foo() {
    let a = await new Promise((resolve,reject)=>{
        resolve("Promise completed");
    })
    console.log(a);
} 
foo();
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda