同步等待 异步等待_哦,是的! 异步/等待

同步等待 异步等待

by Tiago Lopes Ferreira

由Tiago Lopes Ferreira

哦,是的! 异步/等待 (Oh yes! Async / Await)

async/await is the new JavaScript syntax to declare an asynchronous function. It’s built on Promises, but is easier to use.

async / await是用于声明异步函数的新JavaScript语法。 它基于Promises构建,但是更易于使用。

A thorough explanation of Promises is beyond the scope of this article. If you are new to Promises in JavaScript, please see Using promises to learn more. It’s not essential to be an expert on promises, but a good introduction will help you to learn async/await.

对Promises的详尽解释超出了本文的范围。 如果您不熟悉JavaScript中的Promises,请参阅使用Promise了解更多信息。 不一定要成为Promise的专家,但好的入门将有助于您学习async / await

Here is a quick reminder of how to write and use a promise.

这是有关如何编写和使用承诺的快速提醒。

承诺 (Promises)

A Promise represents a value that will be available now, in the future, or (possibly) never.

承诺表示现在,将来或(可能)永远不可用的值。

A Promise state can be one of the following:

Promise状态可以是以下之一:

  • pending — the Promise was neither resolved nor rejected. It represents a Promise‘s initial state.

    待定 -承诺既未解决也未拒绝。 它代表一个承诺的初始状态。

  • resolved — the operation, wrapped by the Promise, completed successfully.

    已解决 -由Promise包装的操作已成功完成。

  • rejected — the operation failed.

    拒绝 -操作失败。

getRandomWithPromise() defines a Promise that resolves with a random number value. setTimeout() simulates a delay to an asynchronous task such as an HTTP request.

getRandomWithPromise()定义一个Promise,该Promise用随机数值解析。 setTimeout()模拟对异步任务(例如HTTP请求setTimeout()的延迟。

Here’s an example of how we can use getRandomWithPromise().

这是我们如何使用getRandomWithPromise()的示例。

异步/等待 (async/await)

async/await is a keyword+operator pair that simplifies asynchronous code.

async / await是关键字+运算符对,可简化异步代码。

  • async declares the function is asynchronous.

    async声明该函数是异步的。

  • await is the operator used to wait for a promise to be fulfilled. It can only be used within an async function.

    等待是用于等待诺言兑现的操作员。 它只能在异步函数中使用。

Let’s build an example, using the getRandomWithAsync() function and async/await.

让我们使用getRandomWithAsync()函数和async / await构建一个示例。

The first thing to notice is the keyword async declares the function is asynchronous

首先要注意的是关键字async声明该函数是异步的

The await operator pauses getRandomWithPromise()until the promise is fulfilled.

等待操作符会暂停getRandomWithPromise()直到实现诺言。

When fulfilled the promise can be:

兑现承诺时可以是:

resolved — meaning that await will return the resolved value.

已解决 -表示await将返回已解决的值。

rejected — meaning that await will throw the rejected value.

拒绝 -表示等待将抛出拒绝值。

Because a promise can throw an unexpected error it is important to wrap our code inside a try/catch block.

由于Promise可能会引发意外错误,因此将我们的代码包装在try / catch块中非常重要。

Note that the body of getRandomWithAsync() reads like it’s a synchronous function. This is one of the advantages of async/await. It makes the code logic easy to follow, even though it’s doing complicated work.

请注意, getRandomWithAsync()的主体读取时就像是一个同步函数。 这是async / await的优点之一。 即使执行复杂的工作,它也使代码逻辑易于遵循。

There’s no longer the need for indentation as with a promise chain.

不再像Promise链那样需要缩进。

等待 (await)

It’s important to remember await can only be used inside an async function. Otherwise, you’ll get a syntax error.

重要的是要记住, 等待只能在异步函数中使用。 否则,您将收到语法错误。

This is how to use await with an Immediately Invoked Function Expression (IIFE).

这就是如何将await与立即调用的函数表达式( IIFE )一起使用。

班级 (Classes)

We can also create async functions inside classes.

我们还可以在类内部创建异步函数。

多重承诺 (Multiple Promises)

What if we have more than one promise to fulfill before continuing?

如果我们在继续之前有一个以上的诺言履行,该怎么办?

We can do it in two ways — sequentially or concurrently.

我们可以通过两种方式进行操作-顺序或并发。

顺序的 (Sequential)

Promise b is only executed after Promise a fulfills. So the function execution time is the sum of execution time for Promises a and b.

承诺b仅在承诺a完成后才执行。 因此,函数执行时间是承诺a和b的执行时间之和。

This can be a major performance issue. The good news is we can run both promises concurrently to save time.

这可能是一个主要的性能问题。 好消息是我们可以同时履行两个承诺以节省时间。

同时 (Concurrent)

We can run both promises in parallel by modifying the code. If you request the random numbers and save the promises, they will run concurrently. We wait for both promises to complete by using await in separate expressions. The result is displayed when they are both complete

通过修改代码,我们可以并行运行这两个承诺。 如果您请求随机数并保存承诺,则它们将同时运行。 我们通过在单独的表达式中使用await等待两个承诺完成。 当它们都完成时显示结果

The function execution time is equal to the promise that takes the longest time.

函数执行时间等于花费最长时间的承诺。

同时(通过Promise.all) (Concurrently (with Promise.all))

We can also use Promise.all for concurrency.

我们也可以使用Promise.all进行并发。

One of the advantages is that Promise.all has fail-fast behavior. If one promise fails, Promise.all will not wait for the other promises to be fulfilled. It rejects immediately.

优点之一是Promise.all具有快速失败的行为。 如果一个承诺失败,Promise.all将不等待另一个承诺被兑现。 它立即拒绝。

等待,然后 (await and thenable)

The use of the await operator is not restricted to promises. await will convert any non-promise value into a promise value. It does it by wrapping the value into Promise.resolve.

等待操作符的使用不限于promise。 await会将任何非承诺值转换为承诺值。 它通过将值包装到Promise.resolve

await can be used with any object that has a .then() method. This object is also known as a thenable.

await可以与任何具有.then()方法的对象一起使用。 此对象也称为thenable

结论 (Conclusion)

We now have the new async/await syntax from JavaScript to write asynchronous code.

现在,我们有了JavaScript的新async / await语法,可以编写异步代码。

async is the keyword that specifies that a function is asynchronous.

async是指定函数异步的关键字。

await is the operator used to wait for a promise to be fulfilled.

等待是用于等待诺言兑现的操作员。

The syntax async/await makes asynchronous code look like synchronous code. This makes the code easier to read and understand.

语法async / await使异步代码看起来像同步代码。 这使代码更易于阅读和理解。

Remember that promises can generate unexpected errors. It’s important to wrap the code inside a try/catch block to handle them.

请记住,承诺会产生意外错误。 将代码包装在try / catch块中以进行处理非常重要。

You can handle multiple promises in two ways: sequential or concurrent. Concurrency has the advantage because promises can run in parallel.

您可以通过两种方式处理多个承诺:顺序或并发。 并发具有优势,因为承诺可以并行运行。

Finally, the operator await is not restricted to promises. We can use it with any object with a .then() method (i.e. a thenable).

最后,操作员等待的时间不仅限于承诺。 我们可以通过.then .then()方法(即thenable)将其与任何对象一起使用。

谢谢 ? (Thanks to ?)

Be sure to check out my articles on ES6

请务必查看我有关ES6的文章

Demystifying ES6 Iterables & IteratorsLet’s demystify JavaScript new way to interact with data structures.medium.freecodecamp.orgLet’s explore ES6 GeneratorsGenerators, aka, an implementation of iterables.medium.freecodecamp.org

揭开ES6迭代器和迭代器 的神秘 面纱 让我们揭开JavaScript与数据结构交互的新方式的神秘 面纱 medium.freecodecamp.org 让我们探讨一下ES6生成 生成 器(又称可迭代对象的实现)。 medium.freecodecamp.org

翻译自: https://www.freecodecamp.org/news/oh-yes-async-await-f54e5a079fc1/

同步等待 异步等待

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值