I am trying to pass an async JS function as a function parameter, but I keep getting an undefined response. I found code in another SO answer which works when not using async/await, but when I tried to modify it to allow async/await I dont get the nested function result "5" returned. Why is this happening, and how can I fix it?
Code example (expected result print "5")
async function foo(x) {
//sleep 5 sec
new Promise((resolve) => setTimeout(resolve, 5000));
console.log(x);
return 5
}
async function bar(func) {
console.log(1)
return await func();
console.log(2)
}
(async()=>{
//alerts "Hello World!" (from within bar AFTER being passed)
let keys=await bar(async function(){ await foo("Hello World!") });
console.log(`result:`,keys)
})()