1

This code is working fine , but I need to add something in timeout function before return in firstFunction()

function LastFunction(){    
    var answer = firstFunction();   
    console.log(answer) 
}

function firstFunction() {
    //Do something;  
    return somevalue 
}

How to add timeout function inside function before return value ?

function firstFunction() {
    setTimeout (function(){
       var something = "something here"
    },1000)
    return something 
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Hunter
  • 1,515
  • 4
  • 15
  • 25

1 Answers1

3

You'll need to use Promises. Your code inside the setTimeout will be delayed but everything outside of it will continue to run synchronously.

function LastFunction(){    
  firstFunction().then(function(val) {
    console.log(val) 
    return val
  })
}

function firstFunction() {
  var promise = new Promise(function(resolve, reject) {
    setTimeout(function(){
        var something = "something here"
        resolve(something)
    },1000)
  })
  return promise
}
Matthew Moran
  • 1,457
  • 12
  • 22
  • Thanks , You mentioned it synchronously so could you please add option with asynchronously way ? @Mathew – Hunter Nov 22 '20 at 20:09
  • 1
    This is `asynchronous`. Javascript is synchronous but when you call `setTimeout` you're scheduling the function you pass in to be called a later time. To get the value, you can use promises which are also asynchronous to wait for the promise to `resolve`. Then by use `.then` you can access that value. – Matthew Moran Nov 22 '20 at 20:14