什么是ES7异步功能?

Kiz*_*zer 3 javascript async-await ecmascript-next

我一直在使用Babel一段时间,我很喜欢它.但是,在主页上列出了支持的功能,它说Async functions.

我做了很多谷歌搜索,而我似乎只能理解它是一个ES7功能.

请问什么是ES7异步功能?

Mar*_*tin 5

异步等待与ES6 Promises一起使用.您可以将它们视为使用Promises编写同步代码的方法.

async关键字标记的方法,这将使异步调用.该await关键字标记的实际调用.

有了一个承诺,你需要将一个方法传递给.then()promise 的方法来处理结果.

function doSomethingAsync() {
    return new Promise((resolve, reject) => {
        // call Rest service and resolve here
    })
}

function printResult() {
    doSomethingAsync()
        .then(result => console.log(result));
}
Run Code Online (Sandbox Code Playgroud)

一切正常.随着Async/Await我们可以把过去的功能略有不同.

async function printResult() {
    let result = await doSomethingAsync();
    console.log(result);
}
Run Code Online (Sandbox Code Playgroud)

这样做的好处是它简单地减少了回调的需要.

欲了解更多信息,请访问:https://www.twilio.com/blog/2015/10/asyncawait-the-hero-javascript-deserved.html