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

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.

主站蜘蛛池模板: 汕尾市| 博野县| 长沙市| 女性| 抚顺县| 汤原县| 崇礼县| 高陵县| 雅江县| 会宁县| 区。| 伽师县| 昭苏县| 康定县| 五大连池市| 东源县| 柘荣县| 双江| 水城县| 成都市| 朝阳市| 包头市| 富源县| 天津市| 通江县| 确山县| 丹棱县| 沙湾县| 普陀区| 封丘县| 奎屯市| 常州市| 清丰县| 宁蒗| 新乡县| 蓝山县| 红原县| 集安市| 蕉岭县| 山丹县| 云南省|