Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

369
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!