DEV Community

nicatspark
nicatspark

Posted on

6 async syntax variations in Javascript.

Using async/await is prefered over the .then syntax since it makes asynchronous code look synchronous and thereby easier to read. And code is all about beeing readable, right? However it's not always super clear where to put that async command.

Async arrow functions look like this:

const foo = async () => {
  // do something
}
Enter fullscreen mode Exit fullscreen mode

Async arrow functions look like this for a single argument passed to it:

const foo = async evt => {
  // do something with evt
}
Enter fullscreen mode Exit fullscreen mode

Async arrow functions look like this for multiple arguments passed to it:

const foo = async (evt, callback) => {
  // do something with evt
  // return response with callback
}
Enter fullscreen mode Exit fullscreen mode

The anonymous form works as well:

const foo = async function() {
  // do something
}
Enter fullscreen mode Exit fullscreen mode

An async function declaration looks like this:

async function foo() {
  // do something
}
Enter fullscreen mode Exit fullscreen mode

Using async function in a callback:

const foo = event.onCall(async () => {
  // do something
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)