官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 嘉祥县| 辽源市| 进贤县| 磐安县| 太湖县| 泽普县| 桐乡市| 揭东县| 漾濞| 十堰市| 安龙县| 酉阳| 昌黎县| 台山市| 留坝县| 铁岭市| 阳信县| 类乌齐县| 承德市| 平顺县| 吉林市| 平乐县| 阳谷县| 大安市| 尚志市| 新沂市| 南和县| 舟曲县| 东乡| 甘孜| 牙克石市| 阿尔山市| 囊谦县| 松溪县| 汽车| 富平县| 铜川市| 黄梅县| 东乌| 黄陵县| 峡江县|