Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - async await

We can use the older technique of using fetch() to call an API asynchronously and also using the .then() method of that promise response object but there is a more modern approach.

The more modern way to consume promises in JavaScript is using await. By labeling the function with await and using async, we can eliminate the use of the .then() method.


const url = 'https://api.github.com';

const FetchData = async () =>
{
    const resp = await fetch(url);
    const jsonData = await resp.json();
    console.log(jsonData);
    document.getElementById("demo").innerHTML =
    `
        ${jsonData.authorizations_url}<br />
        ${jsonData.code_search_url}<br />
        ${jsonData.emails_url}
    `;
};

window.onload = function ()
{
    FetchData();
}