0

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)

})()
Rilcon42
  • 9,584
  • 18
  • 83
  • 167
  • 1
    because the resolve should be setting the value, not using a return. and the function inside of the bar has no return – epascarello Jul 10 '23 at 18:13
  • @epascarello I cant believe I missed that. please post that as a solution......spent waaaaay to long on this dang it. stupid return lol – Rilcon42 Jul 10 '23 at 18:20
  • Side note: You don't need `return await func()`. Just `return func()` will work because returning a promise from an async function _resolves_ the async function promise to the promise returned inside its body. – Yousaf Jul 10 '23 at 18:32
  • @Yousaf interesting, thanks.... I always appreciate making my code a little cleaner! – Rilcon42 Jul 10 '23 at 18:42
  • Your `foo` code is not `await`ing the promise that it constructs? – Bergi Jul 10 '23 at 18:54

1 Answers1

1

You are missing an await on the sleep if you want it to wait 5 seconds. You have no return in the function you are passing in so the function returns undefined.

async function foo(x) {
    //sleep 5 sec
    await 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()=>{
    let keys=await bar(async function(){ return await foo("Hello World!") });
    console.log(`result:`,keys)
})()
epascarello
  • 204,599
  • 20
  • 195
  • 236