How can you call async from non-async function?

I am praticing async and await but It comes to where I want to call async from non-async but this simple program has me completely stuck. Actually I am developer who are new to async/await. How can I get rid of this trouble? I only return output in async function and I want to get/call it in regular function like this: async function makeAsyncData(unknown) { await new Promise(resolve => setTimeout(resolve, 2000)); return unknown; } function getAsyncData(data) { ... } getAsyncData("Data to display...");

»Javascript @youtuber



» 1 answer  » 44 views   


Add photos



Gadrawin • 2 months ago
Since I've just solved problem like this before, I came with this trick. Just treat async call as promise and add .then to it, it will work fine. Lastly, Simply call any number of function getAsyncData("...") and pass data you want and get the result for after 2 seconds.

async function makeAsyncData(unknown) {
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    return unknown; 
    // unknown data we set at runtime
}


function getAsyncData(data) {
    makeAsyncData(data).then((data) => console.log(data));
}

getAsyncData("Data to be returned!");
getAsyncData("More data...");

 »

0  Dislike  •  Reply



Back to top

[SHARE THIS POST]: The post's archived Spread it to others!

Posted under this donnektish »
This community is about sharing contents such as questions and answers discussing about Javascript and TypeScript, ES5, ES6
62 people joined this donnektish



Maintain social distancing, to avoid Covid19