async/await in javascript

async/await in javascript

1. async keyword

async is a keyword which can be used before of a function definition.

async function sayHi() {
  return "Hello There"
}

The word async means one thing: the function that uses it always returns a promise. Other values other then promises are wrapped as promise and resolved by default.

For example in previous example, it will return a promises with returned string. Lets look at it

async function sayHi() {
  return "Hello There!"
}

function log(message) {
  console.log(message)
}

sayHi().then(log) // console > "Hello There"

We could also explicitly return a promise, which works the same way

async function sayHi() {
  return Promise.resolve("Hello There!")
}

sayHi().then(log) // console > "Hello There"

2. await keyword

Right now we see how async function works behind the scenes. But there is another keyword which can only be used inside async functions and that is await

// syntax
async function sayHi() {
    let promise = new Promise((resolve, reject) => { 
      setTimeout(() => { resolve("Hello There!") }, 3000) 
    })

    // wait until promise is resolved
  let result = await promise

  log(result) // console > "Hello There"
}

If we try to use await in a non-async function, there would be a syntax error

3. error-handling on async functions

Because async functions returns promise, if there was a rejection during function process it throws an error just like throw statement.

async function logError() {
  return Promise.reject(new Error("Whoops!"))
}

async function logError() {
  throw new Error("Whoops!")
}

3.1. using try/catch

We can use try/catch statement to handle potential problems in the codebase.

async function logError() {
  return Promise.reject(new Error("Whoops!"))
}

async function sayHi() {
  try {
        await logError()
  } catch (error) {
        // catches the error
        // console -> Whoops!
        console.log(error.message)
  }
}

4. async/await and .then/catch

When we use async/await, we rarely need .then, because await handles the waiting for us. And we can use a regular try..catch instead of .catch. That’s usually (but not always) more convenient.

5. Resources

javascript.info/async-await