Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

368
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda