bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/JavaScript/Objects, Classes, and Advanced Patterns
JavaScript•Objects, Classes, and Advanced Patterns

JavaScript async and await

async and await make promises easier

You still use promises, but you write the code like normal step by step code.

async makes a function return a Promise

await makes a function wait for a Promise

Why async and await Exist

Promise chains can become long.

async and await were created to reduce nesting and improve readability.

Promises Example

// Three functions to run in steps function step1() {
return Promise.resolve("A");
}
function step2(value) {
  return Promise.resolve(value + "B");
}
function step3(value) {
  return Promise.resolve(value + "C");
}
// Run the three functions in steps step1() .then(function(value) {
return step2(value);
}) .then(function(value) {
return step3(value);
}) .then(function(value) {
myDisplayer(value);
});

The same flow with async and await is easier to read.

Example

// Function to run the three functions in steps async function run() {
let v1 = await step1();
let v2 = await step2(v1);
let v3 = await step3(v2);
myDisplayer(v3);
}
run();

The async Keyword

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

This is true even if you return a normal value.

Example

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

Is the same as

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

The result is handled with then() because it is a promise:

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

Example

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

Or simpler, since you expect a normal value (a normal response, not an error):

Example

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

The await Keyword

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

let value = await promise;

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

Example

function step1() {
  return Promise.resolve("A");
}
async function run() {
  let value = await step1();
  myDisplayer(value);
}
run();

Handling Errors with try...catch

Promises use catch() for errors.

async and await use try...catch .

Example

function fail() {
 return Promise.reject("Failed");
}
async function run() {
 try {
 let value = await fail();
 console.log(value);
 } catch (error) {
 console.log(error);
}
}
run();

Errors from awaited promises are caught like normal errors.

Sequential vs Parallel

Awaiting one by one runs tasks in sequence.

This is correct when one step depends on the previous step.

Example

async function run() {
 let a = await step1();
 let b = await step2();
 console.log(a, b);
}

If tasks do not depend on each other, you can run them in parallel.

Use Promise.all() to wait for both.

Example

async function run() {
 let p1 = step1();
 let p2 = step2();
 let values = await Promise.all([p1, p2]);
 console.log(values);
}

Start the promises first.

Await them together.

Real Example with fetch

fetch() returns a promise.

This makes it a perfect example for async and await .

Example

async function loadData() {
 try {
 let response = await fetch("data.json");
 let data = await response.json();
 console.log(data);
 } catch (error) {
 console.log(error);
}
}
loadData();

This is promise-based async code written in a synchronous style.

Common Beginner Mistakes

Using await outside an async function causes an error.

Forgetting try...catch can hide async errors.

When async code fails, check the console and the Network tab.

Browser Support

async/await is an ECMAScript 2017 feature.

ES2017 is supported in all modern browsers since September 2017 :

Chrome 58Edge 15Firefox 52Safari 11Opera 45
Apr 2017Apr 2017Mar 2017Sep 2017May 2017

the next lesson focuses on fetch() and real-world network requests.

You will learn status codes, JSON parsing, and common fetch mistakes.

The Fetch API

Previous

JavaScript Promises

Next

JavaScript fetch API

This chapter

Overview
123

Lessons

539m

Read time

1. JavaScript Objects2. JavaScript Temporal Tutorial3. JavaScript Loops4. JavaScript Advanced Functions5. JavaScript Objects6. JavaScript Temporal Intro7. JavaScript Iterables8. JavaScript Function Definitions9. JavaScript Object Properties10. JavaScript Temporal vs Date11. JavaScript Iterators12. JavaScript Callbacks13. JavaScript Object Methods14. JavaScript Temporal Duration15. JavaScript Generators16. The JavaScript this Keyword17. JavaScript this Keyword18. JavaScript Temporal Instant19. JavaScript Function call()20. JavaScript Display Objects21. JavaScript PlainDateTime22. JavaScript Function apply()23. JavaScript Object Constructors24. JavaScript Temporal PlainDate25. JavaScript Function bind()26. JavaScript PlainYearMonth27. Self-Invoking Functions28. JavaScript PlainMonthDay29. JavaScript Closures30. JavaScript Temporal PlainTime31. JavaScript Objects - Advanced32. JavaScript ZonedDateTime33. JavaScript Object Definitions34. JavaScript Temporal Now35. this in JavaScript Objects36. JS Temporal Arithmetic37. JavaScript Object Iterations38. JS Temporal Differences39. JavaScript Object Accessors40. JS Temporal Compare41. JavaScript Object Management42. JavaScript Temporal Conversion43. JavaScript Object Protection44. Temporal Display Formats45. JavaScript Object Prototypes46. JavaScript Temporal Mistakes47. JavaScript Classes48. Migrate from Date to Temporal49. JavaScript Class Inheritance50. Temporal Standards51. JavaScript Static Methods52. Asynchronous JavaScript53. Asynchronous Programming54. JavaScript Timeouts55. JavaScript Callbacks56. JavaScript Promises57. JavaScript async and await58. JavaScript fetch API59. Debugging Async JavaScript60. JavaScript Modules61. JavaScript Modules Export62. JavaScript Modules Import63. JS Module Namespace64. JavaScript Dynamic Modules65. JavaScript Meta Programming66. JavaScript Reflect67. JavaScript Proxy68. JavaScript Typed Arrays69. Typed Array Methods70. JavaScript ArrayBuffer71. JavaScript DataView72. JavaScript Atomics73. JavaScript HTML DOM Navigation74. JavaScript HTML DOM Elements (Nodes)75. JavaScript HTML DOM Collections76. JavaScript HTML DOM Node Lists77. JavaScript Window - The Browser Object Model78. JavaScript Window Screen79. JavaScript Window Location80. JavaScript Window History81. JavaScript Window Navigator82. JavaScript Popup Boxes83. JavaScript Timing Events84. JavaScript Cookies85. Web APIs - Introduction86. JavaScript Fetch API87. Web Geolocation API88. Web History API89. Pointer Events API90. Web Storage API91. JavaScript Validation API92. Web Workers API93. AJAX Introduction94. AJAX - The XMLHttpRequest Object95. AJAX - XMLHttpRequest96. AJAX - Server Response97. AJAX XML Example98. AJAX PHP Example99. AJAX ASP Example100. AJAX Database Example101. XML Applications102. JavaScript JSON103. JSON Syntax104. JSON vs XML105. JSON Data Types106. JSON.parse()107. JSON.stringify()108. JSON Object Literals109. JSON Array Literals110. JSON PHP111. JSON HTML112. JSONP113. JavaScript / jQuery DOM Selectors114. JavaScript / jQuery HTML Elements115. JavaScript / jQuery CSS Styles116. JavaScript / jQuery HTML DOM117. JavaScript Graphics118. HTML Canvas119. Plotly.js120. Chart.js121. Google Chart122. D3.js123. JavaScript Interview Preparation

On this page

Why async and await ExistThe async KeywordThe await KeywordHandling Errors with try...catchSequential vs ParallelReal Example with fetchCommon Beginner MistakesBrowser Support