Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
110
rated 0 times [  116] [ 6]  / answers: 1 / hits: 162879  / 10 Years ago, thu, july 24, 2014, 12:00:00

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());

More From » return

 Answers
68

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


function x() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('done!');
});
});
}

x().then((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!';
}

[#70062] Wednesday, July 23, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevenjeffreyr

Total Points: 286
Total Questions: 112
Total Answers: 95

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;