Categories
Modern JavaScript

Best Features of ES2017 — Async Functions

Spread the love

Since 2015, JavaScript has improved immensely.

It’s much more pleasant to use it now than ever.

In this article, we’ll look at the best features of ES2017.

Async Functions

Async functions is one big feature released with ES2017.

It’s a useful shorthand for the then method.

We can declare async functions in the following ways:

  • async function declarations: async function foo() {}
  • async function expressions: const foo = async function () {};
  • async method definitions: let obj = { async foo() {} }
  • async arrow functions: const foo = async () => {};

Async functions always return promises.

So if we have:

async function asyncFunc() {
  return 'foo';
}

then asyncFunc returns a promise that resolves to 'foo' .

Then we can use it by writing:

asyncFunc()
  .then(x => console.log(x));

To reject a promise, we throw an error:

async function asyncFunc() {
  throw new Error('error');
}

Then we can catch the error by writing:

asyncFunc()
  .catch(x => console.log(x));

We can handle results and errors of promises with await .

The await operator is only allowed in async functions.

It waits for its operand, which is always a promise to be settled.

If the promise is fulfilled, then the result of await is its fulfillment value.

If the promise is rejected, then await throws the rejection value.

So we can write:

async function asyncFunc() {
  const result = await promise;
  console.log(result);
}

where promise is the promise we’re waiting for the result of.

That’s the same as:

async function asyncFunc() {
  return promise
    .then(result => {
      console.log(result);
    });
}

The good thing with this syntax is that we can handle multiple promises in a shorter way.

So we can write:

async function asyncFunc() {
  const result1 = await promise1();
  console.log(result1);
  const result2 = await promise2();
  console.log(result2);
}

That’s the same as:

function asyncFunc() {
  return promise1()
    .then(result1 => {
      console.log(result1);
      return promise2();
    })
    .then(result2 => {
      console.log(result2);
    });
}

As we can see, it’s much shorter.

To run multiple promises in parallel, we can use Promise.all :

async function asyncFunc() {
  const [result1, result2] = await Promise.all([
    promise1(),
    promise2(),
  ]);
  console.log(result1, result2);
}

This is the same as:

async function asyncFunc() {
  return Promise.all([
      promise1(),
      promise2(),
    ])
    .then(([result1, result2]) => {
      console.log(result1, result2);
    });
}

To handle errors, we use try-catch as we do with synchronous functions:

async function asyncFunc() {
  try {
    await promiseFunc();
  } catch (err) {
    console.error(err);
  }
}

This is the same as:

function asyncFunc() {
  return promiseFunc()
    .catch(err => {
      console.error(err);
    });
}

Async function works by using generators to wait for the result until it continues execution.

It waits for the result each time the await operator is added.

Once the promise is fulfilled, then the async function continues to run.

Async functions are started synchronously and settled asynchronously.

The result of an async function is always a promise.

The promise is created when the async function starts.

The body of it is then run.

It may finish with return or throw .

Or it may be paused with await and continues once the result is obtained.

Then finally, the promise is returned.

Conclusion

Async functions is a great shorthand for writing promise code.

These are functions that always return promises.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *