Async and Await in JavaScript
Published by
sanya sanya
Async
and Await
are the special syntaxes used to work with promises in Javascript in a comfortable manner.
Both the keywords Async and Await are used with promises in Javascript many times.
Async
Async
is written before the function when used and it has a special functionality that when Async will be used it will always return a promise. All the other values will be wrapped with resolved automatically when async is used with a function.
The code example of the Async
function is mentioned below -
async function func() { return 1; }
Async can be used with other methods too. However, the code example of async
with .then()
is mentioned below -
async function func() { return Promise.resolve(1); } func().then(alert);
Output: The promise will be fulfilled and 1 will be returned as an output in the alert window.
Await
When we use Await
with the promise it will keep the Javascript waiting until the Promise settles and returns the result.
The syntax of the await
is mentioned below -
let promise = await Promise;
The code with execution using the await
with promises is mentioned below -
async function func() { let promise = new Promise((resolve, reject) => { setTimeout(() => resolve("Function Executed..!"), 2000) }); let result = await promise; alert(result); } func();
//Output: Function Executed..! will be printed after 2 seconds.
Await will not work if the function is non-async. For instance,
function func() { let pro = Promise.resolve(1); let result = await promise; }
//Output: Syntax Error
There will be a syntax error because the function is non-async. However, this can be resolved using the async keyword before the function.
Error Handling
The Error Handling
is the concept that occurs when a await promise raises the error. It throws the error mentioned below -
async function func() { throw new Error("Error"); }
The throw
keyword is used here to be used for throwing an error. This can also be done using try and catch as mentioned below -
async function func() { try { let response = await fetch('https://www.google.com'); } catch(err) { alert(err); } } func();
Library
WEB DEVELOPMENT
Basic
HTML - Hyper Text Markup Language
CSS - Cascading Style Sheets
JavaScript
An Introduction to Javascript!
How to Run JavaScript Code
Variables in Javascript
Numbers in JavaScript
JavaScript Operators
Data Types in JavaScript
Conditional Statements
Switch Statements
Loops in Javascript
Arrays in JavaScript
Strings in JavaScript
Objects in JavaScript
Object Methods in JavaScript
Functions in JavaScript
Object Referencing and Copying in JavaScript
' this' keyword
Asynchronous Programming in JavaScript
Callbacks in JavaScript
Promises in JavaScript
Constructor Functions in JavaScript
Async and Await in JavaScript
Type Conversion in Javascript
DOM
Currying in JavaScript
Network Request
Frontend
Backend
Interview Questions
FAANG QUESTIONS
On this page
Async
Await
Error Handling