Home > Net >  Is there a way to execute asynchronous code inline within a synchronous function?
Is there a way to execute asynchronous code inline within a synchronous function?

Time:08-29

Whenever I look for async/await JavaScript examples called from within a synchronous thread, I always see the following structure:

async fun = () => {
  // async stuff like await statements
  console.log("Done!")
}

fun() // Will print "Done!" when the end of the process has been reached

However I've recently come across a situation where I would want to write code inline without explicitly declaring a function and then calling it (avoids passing arguments if the function is declared in a higher scope and in my opinion is cleaner). I've found this solution to work, but I don't like it as it's essentially the same thing, simply the function isn't given a name:

(async () => {
  // async stuff like await statements
  console.log("Done!")
}).call() // Will also print "Done!" when the end of the process has been reached

Is there a better way to execute inline asynchronous code ? I looked at using the Promise API, notably Promise.resolve() but it doesn't seem to execute an asynchronous function passed to it, it's quite likely I still don't understand how it works.

CodePudding user response:

I usually use IIFE

(async () => {
  // async stuff like await statements
  console.log("Done!")
})()
  • Related