DEV Community

Falah Al Fitri
Falah Al Fitri

Posted on

Javascript: Async/Await

"async and await make promises easier to write"

async makes a function return a Promise

await makes a function wait for a Promise


Async Syntax

The keyword async before a function makes the function return a promise:

async function myFunction() {

    // "Producing Code" (May take some time)

    return "Hello World"

}
Enter fullscreen mode Exit fullscreen mode

Here is how to use the Promise:

// "Consuming Code" (Must wait for a fulfilled Promise)
myFunction().then(

    function( success ) { 

        /* code if successful */ 
        console.log( success )

    },

    function( error ) { 

        /* code if some error */ 
        console.error( error )

    }

)
Enter fullscreen mode Exit fullscreen mode

Example

1


2 Display


Await Syntax

The await keyword can only be used inside an async function.

The await keyword makes the function pause the execution and wait for a resolved promise before it continues:

let value = await promise
Enter fullscreen mode Exit fullscreen mode

Example

1


2 Display


3 Waiting for a file


4 Waiting for a file - return


Async Function (developer.mozilla.org)

The async function declaration declares an async function where the await keyword is permitted within the function body. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

...

Top comments (0)