+ 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
1 Resposta
+ 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.