- Hands-On Machine Learning with JavaScript
- Burak Kanber
- 268字
- 2021-06-25 21:38:19
The async/await functions
The async and await keywords are not an ES6 feature but rather an ES8 feature. While promises bring huge improvements to the way we deal with asynchronous calls, promises also are susceptible to lots of method chaining, and in some cases force us to use asynchronous paradigms when we really just want to write a function that acts asynchronously but reads as if it were a synchronous function.
Now let's take a look at the following example from MDN's asynchronous function reference page (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function):
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
var result = await resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
}
asyncCall();
The resolveAfter2Seconds function is a normal JavaScript function that returns an ES6 promise. The magic is in the asyncCall function, which is marked by the async keyword. Inside asyncCall, we invoke resolveAfter2Seconds with the await keyword, rather than using the more familiar promise .then(result => console.log(result)) construct we'd normally use in ES6. The await keyword makes our async function wait for the promise to resolve before continuing, and returns the result of the Promise directly. In this manner, async/await can convert asynchronous functions that use promises to read like synchronous functions, which should help keep deeply nested promise calls and asynchronous function stats neat and easy to read.
The async and await features are part of ES8, not ES6, so when we set up Babel in a few minutes we'll need to be sure to include all new versions of EMCAScript in our configuration, not just ES6.
- 腦動力:C語言函數速查效率手冊
- 手把手教你玩轉RPA:基于UiPath和Blue Prism
- Learning Social Media Analytics with R
- ServiceNow Cookbook
- 大數據改變世界
- 機艙監測與主機遙控
- ROS機器人編程與SLAM算法解析指南
- 21天學通ASP.NET
- 工業機器人現場編程(FANUC)
- Mastering Machine Learning Algorithms
- 80x86/Pentium微型計算機原理及應用
- 21天學通Visual Basic
- Hands-On Data Warehousing with Azure Data Factory
- 計算機組裝與維修實訓
- Redash v5 Quick Start Guide