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

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.

主站蜘蛛池模板: 南乐县| 柯坪县| 新安县| 广汉市| 隆安县| 高阳县| 千阳县| 石泉县| 桐庐县| 云南省| 洛扎县| 桃江县| 周口市| 军事| 隆回县| 府谷县| 布尔津县| 右玉县| 辽中县| 葫芦岛市| 鄢陵县| 兰州市| 武义县| 渭南市| 达州市| 万州区| 保靖县| 内乡县| 镇江市| 句容市| 金平| 荔波县| 连城县| 威海市| 仙桃市| 肇东市| 探索| 伊宁县| 晋宁县| 乐陵市| 麦盖提县|