Learn Asynchronous JavaScript - Async-Await Cheatsheet - Codecademy
Learn Asynchronous JavaScript - Async-Await Cheatsheet - Codecademy
Async-Await
Resolving JavaScript Promises
When using JavaScript async...await , multiple
asynchronous operations can run concurrently. If the let promise1 = Promise.resolve(5);
resolved value is required for each promise initiated, let promise2 = 44;
Promise.all() can be used to retrieve the resolved let promise3 = new
value, avoiding unnecessary blocking. Promise(function(resolve, reject) {
setTimeout(resolve, 100, 'foo');
});
Promise.all([promise1, promise2,
promise3]).then(function(values) {
console.log(values);
});
// expected output: Array [5, 44, "foo"]
Asynchronous JavaScript function
An asynchronous JavaScript function can be created with
the async keyword before the function name, or function helloWorld() {
before () when using the async arrow function. An return new Promise(resolve => {
async function always returns a promise. setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}
try {
let user = JSON.parse(json); // <-- no
errors
alert( user.name ); // no name!
} catch (e) {
alert( "Invalid JSON data!" );
}
JavaScript aysnc await operator
The JavaScript async...await syntax in ES6 o ers a new
way write more readable and scablable code to handle function helloWorld() {
promises. A JavaScript async function can contain return new Promise(resolve => {
statements preceded by an await operator. The setTimeout(() => {
operand of await is a promise. At an await expression, resolve('Hello World!');
the execution of the async function is paused and waits
}, 2000);
for the operand promise to resolve. The await operator
});
returns the promise’s resolved value. An await operand
}
can only be used inside an async function.