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

250
Visualizações
Why do I have to use await to get the result of the promise?
const delay = ms => new Promise(res => setTimeout(res, ms));

async function notInstant() {
  await delay(1);
  return 1;
}

(async function() {
 let a = notInstant();
 console.log(a);
 await delay(10000);
 console.log("Still a promise after 10 seconds even though the function only waits for 1 millisecond =>", a);
 a = await a;
 console.log("Printing directly after but now is resolved with the correct value", a);
})();

I know that I shouldn't rely on setTimeout for these kinds of things, but I don't understand why printing the result after 10 seconds still gives an unresolved promise even though the function called only waits for 1 millisecond before returning a value. Then using await makes the result directly available for some reason.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

This example illustrates the principle you're observing:

let a = {};
console.log(a);
a.val = 1;
console.log(typeof a); // still an object even though `a` has a value
a = a.val;
console.log(typeof a); // now it's a number

The original promise returned from notInstant will always be a promise. await basically extracts the resolved value from the promise for you. The only reason a ends up being a value in your example is that you're setting it to the result of the await expression.

If you wanted to set a to the result of its promise when it completes, but avoid awaiting it, you could use its then method to affect a state change, like this:

const delay = ms => new Promise(res => setTimeout(res, ms));

async function notInstant() {
  await delay(1);
  return 1;
}

(async function() {
 let a = notInstant();
 console.log(a);
 a.then(n => a = n);
 await delay(1000); 
 console.log("a has its value now; we waited long enough", a);
})();

That's probably not a great pattern to follow (reusing the variable to represent both the promise and the value), but hopefully it helps teach the principle.

about 4 years ago · Juan Pablo Isaza Relatório

0

from the docs:

The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

So, as mentioned by DaveG, with out calling the await, you are just holding the promise

about 4 years ago · Juan Pablo Isaza Relatório

0

Notice that async functions return a promise.
And you need await to get the value of the promise.


here is what MDN says about it:

Async Function's Return value

A Promise which will be resolved with the value returned by the async function, or rejected with an exception thrown from, or uncaught within, the async function.

about 4 years ago · Juan Pablo Isaza 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