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

370
Visualizações
Return values from SetTimeout function ( Promise.Then())

In the code below , Values are RETURNED correctly from a queued Promise.then() chain .

CODE:

let cond_1 = true;
let data = 'Data Received....';
let err  = 'Error';

var p1 = new Promise(function(resolve,reject){ 
    if(cond_1){
        resolve(data);
    }else{
        reject(err); }})

p1.then((data)=>{console.log(data);return 'Wait....';})
.then((val1)=>{console.log(val1); return 'Finished';})
.then((val2)=>{console.log(val2)})
.catch((err)=>{console.log(err)});

Output :

Data Received....
Wait....
Finished

However, the same RETURNED values from a chained SetTimeout function are returned 'UNDEFINED'.

CODE:

p1.then((data)=>{console.log(data); return 'Wait.....'; })
.then((val1)=>{setTimeout(function(val1){console.log(val1); return 'Finished';},1000)})
.then((val2)=>{setTimeout(function(val2){console.log(val2);},1000)})
.catch((err)=>{console.log(err)});

Output:

Data Received....
undefined
undefined

How to resolve this?

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

0

Try taking advantage of Lexicographic nature of Javascript.

Instead of making a function v1,v2 which your functions takes within setTimeout, just use an arrow function. In this way you are using the v1,v2 returned from promise.

Do this

let cond_1 = true;
let data = 'Data Received....';
let err = 'Error';

var p1 = new Promise(function(resolve, reject) {
  if (cond_1) {
    resolve(data);
  } else {
    reject(err);
  }
})

p1.then((data) => {
    console.log(data);
    return 'Wait.....';
  })
  .then((val1) => {
    setTimeout(() => {
      console.log(val1);
    }, 1000);
    return 'Finished';
  })
  .then((val2) => {
    return setTimeout(() => {
      console.log(val2)
    }, 1000)
  })
  .catch((err) => {
    console.log(err)
  });

What you did was you created a new variable v1,v2 for your function. You can only use that when you pass value v1,v2 in that function. That function won't use v1,v2 returned from promise as you expect.

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