什么是ES7异步功能? [英] What are ES7 Async functions?

查看:212
本文介绍了什么是ES7异步功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用Babel一段时间,我很喜欢它。但是,在主页上列出了支持的功能,它显示异步功能

I have been using Babel for a while now, and I am loving it. However, on the home page, where it lists the supported features, it says Async functions.

我做过很多谷歌搜索,我似乎都明白这是一个ES7功能。

I have done a lot of Googling, and all I can seem to understand is that it's an ES7 feature.

请问什么是ES7异步功能?

Please what are ES7 Async functions?

推荐答案

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

Async Await work with ES6 Promises. You can think of them as a way to write synchronous like code with Promises.

async 关键字标记为将进行异步调用的方法。 await 关键字标记实际呼叫。

The async keyword marks as method that will make an asynchronous call. The await keyword marks the actual call.

您需要将一个方法传递给承诺要处理的 .then()方法结果。

With a promise you need to pass a method to the .then() method of the promise to to handle the result.

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

function printResult() {
    doSomethingAsync()
        .then(result => console.log(result));
}

一切正常。使用 Async / Await ,我们可以将最后一个函数编写得有点不同。

This all works fine. With Async/Await we can write the last function a little different.

async function printResult() {
    let result = await doSomethingAsync();
    console.log(result);
}

这样做的好处是它简单地减少了对回调的需求。

The benefit of this is it simply reduces the need for callbacks.

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

For more see: https://www.twilio.com/blog/2015/10/asyncawait-the-hero-javascript-deserved.html

这篇关于什么是ES7异步功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆