Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass an ASYNC JavaScript function as parameter

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)

})()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
})()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading