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

234
Visualizações
How can we store the values resolved by a JavaScript Promise?

I am currently learning async JavaScript, and I am confused about how to get the values retured by a promise my code:

let p  = Promise.resolve("Passed")

let x = p.then(msg=>msg).catch(msg=>msg)
setTimeout(()=>console.log(x), 2)
console.log(x)

Output:

Promise { <pending> }
Promise { 'Passed' }

How can I get the string "Passed" which is being returned by the .then function, and why the promise is pending even when the Promise is resolved? But when we console.log its value using a setTimeout function is gives its value, and How to get the "Passed" from Promise { 'Passed' }

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

0

You are intended to use promises this way:

p.then((x) => {
    console.log(x);
});

or this way (only works in async functions):

x = await p;

Normally, p would actually be a function that returns a promise, like this:

function p() {
    return new Promise((resolve, reject) => {
        resolve("message");
    });
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You cannot get a response out of promise right now. To solve you can use 2 approaches:

subscribe inside of then with a new function which gets the promise result // but it would be asynchronously like this

var p = Promise.resolve([1,2,3]);
p.then(function(v) {
  console.log(v[0]); // 1
});

second one is : use async function with await structure

async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // in this part it will be wait until promise will end its work

  alert(result); // "done!"
}

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