+ 1

Why doesn't my code work right? Can you please explain what I did wrong?

I can receive the right output in the console, but can't return the value: function getNum(num, cb) { setTimeout(() => cb(num), 1000); } function plusTen(num) { return getNum(num, (arg) => { console.log(`result: ${arg + 10}`); //output: result: 15 return arg + 10; // nothing }); } console.log(plusTen(5)); // undefined

18th Jul 2020, 8:36 PM
Nika Nika
1 Answer
+ 17
getNum doesn't return anything, that's why the output is undefined. Adding a return statement to this function won't help you, because setTimeout returns timer id. You can either pass a callback to the calling function like this: plusTen(5, (getNumResult) => doSomethingWithResult); and then call it instead of "return arg +10": cb(arg + 10) ... or you can use Promises.
18th Jul 2020, 10:00 PM
Igor Makarsky
Igor Makarsky - avatar