0% found this document useful (0 votes)
9 views

JavaScript Async Await

The document discusses async/await syntax in JavaScript. Async functions return promises and await pauses execution until a promise is resolved. Examples demonstrate defining async functions and using await with promises.

Uploaded by

Valerian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

JavaScript Async Await

The document discusses async/await syntax in JavaScript. Async functions return promises and await pauses execution until a promise is resolved. Examples demonstrate defining async functions and using await with promises.

Uploaded by

Valerian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Async Syntax

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

Example
async function myFunction() {
return "Hello";
}

Is the same as:

function myFunction() {
return Promise.resolve("Hello");
}

Here is how to use the Promise:

myFunction().then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);

Example
async function myFunction() {
return "Hello";
}
myFunction().then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);

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;

Example
Basic Syntax
async function myDisplay() {
let myPromise = new Promise(function(resolve, reject) {
resolve("I love You !!");
});
document.getElementById("demo").innerHTML = await myPromise;
}

myDisplay();
The two arguments (resolve and reject) are pre-defined by JavaScript.

We will not create them, but call one of them when the executor function is
ready.

Very often we will not need a reject function.

Example without reject


async function myDisplay() {
let myPromise = new Promise(function(resolve) {
resolve("I love You !!");
});
document.getElementById("demo").innerHTML = await myPromise;
}

myDisplay();

Waiting for a Timeout


async function myDisplay() {
let myPromise = new Promise(function(resolve) {
setTimeout(function() {resolve("I love You !!");}, 3000);
});
document.getElementById("demo").innerHTML = await myPromise;
}

myDisplay();

You might also like