Say I have a function which returns the result on an input after 1 sec:
function slowDouble(num) {
setTimeout(() => {
return num * 2;
}, 1000);
}
Now I want to call this function and wait until the result is returned, so I can do other operations on it. I tried to wrap this function in a Promise but the result is returned to then block after the log statement is executed (printing undefined):
function promisify(num) {
return new Promise((resolve) => {
var res = slowDouble(num);
resolve(res);
});
}
function promisifyTest(num) {
promisify(num).then((res) => {
console.log('then result ', res);
})
}
promisifyTest(4); // undefined
Then I tried to use await:
async function asyncCallToAPI(num) {
var tt = await promisify(num);
console.log('async result', tt);
}
asyncCallToAPI(3); // undefined
and got the same undefined result back.
I know this is very similar to other questions asked here but I couldn't figure this out yet.