Get return value from setTimeout

Vainglory07 picture Vainglory07 · Jul 24, 2014 · Viewed 93k times · Source

I just want to get the return value from setTimeout but what I get is a whole text format of the function?

function x () {
    setTimeout(y = function () {
        return 'done';
    }, 1000);
    return y;
}

console.log(x());

Answer

Matt Clarkson picture Matt Clarkson · Jul 24, 2014

You need to use Promises for this. They are available in ES6 but can be polyfilled quite easily:

function x() {
   var promise = new Promise(function(resolve, reject) {
     window.setTimeout(function() {
       resolve('done!');
     });
   });
   return promise;
}

x().then(function(done) {
  console.log(done); // --> 'done!'
});

With async/await in ES2017 it becomes nicer if inside an async function:

async function() {
  const result = await x();
  console.log(result); // --> 'done!';
}