Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Async/Await cheatsheet

(reference : https://tutorialzine.com/2017/07/javascript-async-await-explained)

Async - declares an asynchronous function (async function someName(){...}).

  • Automatically transforms a regular function into a Promise.

  • When called async functions resolve with whatever is returned in their body.

  • Async functions enable the use of await.

Await - pauses the execution of async functions. (var result = await someAsyncCall();).

  • When placed in front of a Promise call, await forces the rest of the code to wait until that Promise finishes and returns a result.

  • Await works only with Promises, it does not work with callbacks.

  • Await can only be used inside async functions.


function getJSON(){

    // To make the function blocking we manually create a Promise.
    return new Promise( function(resolve) {
        axios.get('https://tutorialzine.com/misc/files/example.json')
            .then( function(json) {

                // The data from the request is available in a .then block
                // We return the result using resolve.
                resolve(json);
            });
    });

}

// Async/Await approach

// The async keyword will automatically create a new Promise and return it.
async function getJSONAsync(){

    // The await keyword saves us from having to write a .then() block.
    let json = await axios.get('https://tutorialzine.com/misc/files/example.json');

    // The result of the GET request is available in the json variable.
    // We return it just like in a regular synchronous function.
    return json;
}```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.