- 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.
- 大數(shù)據(jù)導(dǎo)論:思維、技術(shù)與應(yīng)用
- 大數(shù)據(jù)戰(zhàn)爭:人工智能時代不能不說的事
- Mastering VMware vSphere 6.5
- 輕松學(xué)PHP
- Dreamweaver CS3網(wǎng)頁制作融會貫通
- 控制與決策系統(tǒng)仿真
- Mobile DevOps
- Pig Design Patterns
- 精通特征工程
- Dreamweaver CS6中文版多功能教材
- Salesforce Advanced Administrator Certification Guide
- 網(wǎng)絡(luò)服務(wù)器搭建與管理
- 數(shù)字多媒體技術(shù)基礎(chǔ)
- Moodle 2.0 Course Conversion(Second Edition)
- Mastering DynamoDB