JavaScript


Async functions (async/await) 8

1
2
3
E4X
5
5.1
6
7
8

This draft deletes the entire topic.

Introduction

Introduction

expand all collapse all

Examples

  • 17

    A function defined as async is a function that can perform asynchronous actions but still look synchronous. The way it's done is using the await keyword to pause the function while it waits for a Promise to resolve/reject.

    Note: Async functions are a Stage 4 ("Finished") proposal on track to be included in the ECMAScript 2017 standard.

    async function getJSON(url) {
        const response = await fetch(url);
        return await response.json();
    }
    

    An async function always returns a Promise itself, so you can use it in other asynchronous functions.

  • 20

    You have to keep the operator precedence in mind when using await keyword.

    Imagine that we have an asynchronous function getUnicorn() which returns a Promise that resolves to an instance of class Unicorn. Now we want to get the size of the unicorn using the getSize() method of that class.

    Look at the following code:

    await getUnicorn().getSize()
    

    At first sight it looks valid, but actually it's not. Due to operator precedence, it's equivalent to the following:

    await (getUnicorn().getSize())
    

    Here we attempt to call getSize() method of the Promise object, which isn't what we want.

    Instead, we should use brackets to denote that we first want to wait for the unicorn, and then call getSize() method of the result:

    (await getUnicorn()).getSize()
    

    Of course the previous version could be valid in some cases, for example if the getUnicorn() function was synchronous, but the getSize() method was asynchronous.

  • Improvements requested:

    • Other: The rewritten example it will not work because `.json()` returns a promise and it will return an error when you will do response.success ([See the documentation](https://developer.mozilla.org/en-US/docs/Web/API/Body/json)) –  Andrici Cezar Oct 6 at 14:58
    12

    Consider the following function using promises:

    function newUnicorn() {
      return fetch('unicorn.json')            // fetch unicorn.json from server
      .then(response => response.json())      // parse the response as JSON
      .then(unicorn =>
        fetch('new/unicorn', {                // send a request to 'new/unicorn' 
            method: 'post',                   // using the POST method
            body: JSON.stringify({unicorn})   // pass the unicorn to the request body
        })
      )
      .then(response => response.json())
      .then(response => response.success)     // return success property of response
      .catch(err => console.log('Error creating unicorn:', err));
     }
    

    The function can be rewritten using async / await as follows:

    async function newUnicorn() {
      try {
        const unicorn = (await fetch('unicorn.json')).json()
        const response = (
          await fetch('new/unicorn', {
              method: 'post',
              body: JSON.stringify({unicorn})
          })
        ).json()
        return response.success
      } catch (err) {
        console.log('Error creating unicorn:', err);
      }
    }
    

    Basically, the await keyword allows you to use asynchronous functions (that is, functions that return promises) as if they were synchronous. Note that you can only use await in async functions. You can also use an async IIFE if you want to execute that code immediately:

    (async () => {
      await makeCoffee()
      console.log('coffee is ready!')
    })()
    
Please consider making a request to improve this example.

Syntax

  • async function foo() {
       ...
       await asyncCall()
    }
  • async function() { ... }
  • async() => { ... }
  • (async () => {
       const data = await asyncCall()
       console.log(data) })()

Parameters

Parameters

Remarks

Async functions are a sugar over promises. They help you make your code more readable and more linear-looking, with less levels of indentation. They do not, however, replace the Promise type, and the lowest level function still probably need to be written with the Promise constructor.

This is not yet a definitive feature of the language, it is currently in stage 3 (candidate) status , this means:

The proposal is mostly finished and now needs feedback from implementations and users to progress further.

Source

Still have a question about Async functions (async/await)? Ask Question

Topic Outline