异步回调地狱_如何逃避异步/等待地狱

异步回调地狱

async/await freed us from callback hell, but people have started abusing it — leading to the birth of async/await hell.

async / await使我们从回调地狱中解脱出来,但是人们已经开始滥用它-导致async / await地狱的诞生。

In this article, I will try to explain what async/await hell is, and I’ll also share some tips to escape it.

在本文中,我将尝试解释什么是异步/等待地狱,并且还将分享一些技巧以逃避它。

什么是异步/等待地狱 (What is async/await hell)

While working with Asynchronous JavaScript, people often write multiple statements one after the other and slap an await before a function call. This causes performance issues, as many times one statement doesn’t depend on the previous one — but you still have to wait for the previous one to complete.

在使用异步JavaScript时,人们经常一个接一个地编写多个语句,并在函数调用之前先等待 。 这会导致性能问题,因为很多时候一个语句不依赖于前一个语句,但是您仍然必须等待上一个语句完成。

一个异步/等待地狱的例子 (An example of async/await hell)

Consider if you wrote a script to order a pizza and a drink. The script might look like this:

考虑一下您是否编写了脚本来订购比萨饼和饮料。 该脚本可能如下所示:

On the surface it looks correct, and it does work. But this is not a good implementation, because it leaves concurrency out of the picture. Let’s understand what its doing so that we can nail down the issue.

从表面上看,它是正确的,并且确实起作用。 但这不是一个很好的实现,因为它使并发不存在。 让我们了解一下它在做什么,以便我们可以找出问题所在。

说明 (Explanation)

We have wrapped our code in an async IIFE. The following occurs in this exact order:

我们已经将代码包装在异步IIFE中 。 以这种确切的顺序发生以下情况:

  1. Get the list of pizzas.

    获取比萨饼列表。
  2. Get the list of drinks.

    获取饮料清单。
  3. Choose one pizza from the list.

    从列表中选择一个披萨。
  4. Choose one drink from the list.

    从列表中选择一种饮料。
  5. Add the chosen pizza to the cart.

    将选定的比萨饼添加到购物车。
  6. Add the chosen drink to the cart.

    将所选的饮料添加到购物车。
  7. Order the items in the cart.

    订购购物车中的物品。
那怎么了? (So what’s wrong ?)

As I stressed earlier, all these statements execute one by one. There is no concurrency here. Think carefully: why are we waiting to get the list of pizzas before trying to get the list of drinks? We should just try to get both the lists together. However when we need to choose a pizza, we do need to have the list of pizzas beforehand. The same goes for the drinks.

正如我之前强调的那样,所有这些语句都一个接一个地执行。 这里没有并发。 仔细想想:为什么我们要先获得比萨饼清单,然后再尝试获取饮料清单? 我们应该尝试将两个列表放在一起。 但是,当我们需要选择披萨时,我们确实需要事先获得披萨列表。 饮料也一样。

So we can conclude that the pizza related work and drink related work can happen in parallel, but the individual steps involved in pizza related work need to happen sequentially (one by one).

因此,我们可以得出结论,与比萨饼相关的工作和与饮料相关的工作可以并行进行,但是与比萨饼相关的工作中涉及的各个步骤需要依次进行(一个接一个)。

错误执行的另一个例子 (Another example of bad implementation)

This JavaScript snippet will get the items in the cart and place a request to order them.

这个JavaScript程式码片段将把商品放入购物车中,并提出订购要求。

async function orderItems() {
  const items = await getCartItems()    // async call
  const noOfItems = items.length
  for(var i = 0; i < noOfItems; i++) {
    await sendRequest(items[i])    // async call
  }
}

In this case, the for loop has to wait for the sendRequest() function to complete before continuing the next iteration. However, we don’t actually need to wait. We want to send all the requests as quickly as possible and then we can wait for all of them to complete.

在这种情况下,for循环必须等待sendRequest()函数完成才能继续下一次迭代。 但是,我们实际上不需要等待。 我们希望尽快发送所有请求,然后我们可以等待所有请求完成。

I hope that now you are getting closer to understanding what is async/await hell and how severely it affects the performance of your program. Now I want to ask you a question.

我希望现在您可以进一步了解什么是异步/等待地狱,以及它如何严重影响程序的性能。 现在我想问你一个问题。

如果我们忘记了await关键字怎么办? (What if we forget the await keyword ?)

If you forget to use await while calling an async function, the function starts executing. This means that await is not required for executing the function. The async function will return a promise, which you can use later.

如果您在调用异步函数时忘记使用await ,该函数将开始执行。 这意味着执行功能不需要等待。 异步函数将返回一个Promise,您可以稍后使用。

(async () => {
  const value = doSomeAsyncTask()
  console.log(value) // an unresolved promise
})()

Another consequence is that the compiler won’t know that you want to wait for the function to execute completely. Thus the compiler will exit the program without finishing the async task. So we do need the await keyword.

另一个结果是,编译器不会知道您要等待函数完全执行。 因此,编译器将在不完成异步任务的情况下退出程序。 所以我们确实需要await关键字。

(async () => {
  const promise = doSomeAsyncTask()
  const value = await promise
  console.log(value) // the actual value
})()

One interesting property of promises is that you can get a promise in one line and wait for it to resolve in another. This is the key to escaping async/await hell.

Promise的一个有趣特性是,您可以在一行中获得一个Promise,然后在另一行中等待它解决。 这是逃避异步/等待地狱的关键。

As you can see, doSomeAsyncTask() is returning a promise. At this point doSomeAsyncTask() has started its execution. To get the resolved value of the promise, we use the await keyword and that will tell JavaScript to not execute the next line immediately, but instead wait for the promise to resolve and then execute the next line.

如您所见, doSomeAsyncTask()返回了一个doSomeAsyncTask() 。 此时, doSomeAsyncTask()已开始执行。 为了获得promise的解析值,我们使用await关键字,它将告诉JavaScript不要立即执行下一行,而是等待promise解析后再执行下一行。

如何摆脱异步/等待地狱? (How to get out of async/await hell ?)

You should follow these steps to escape async/await hell.

您应该按照以下步骤逃避异步/等待地狱。

查找依赖于其他语句执行的语句 (Find statements which depend on the execution of other statements)

In our first example, we were selecting a pizza and a drink. We concluded that, before choosing a pizza, we need to have the list of pizzas. And before adding the pizza to the cart, we’d need to choose a pizza. So we can say that these three steps depend on each other. We cannot do one thing until we have finished the previous thing.

在第一个示例中,我们选择披萨和饮料。 我们得出的结论是,在选择披萨之前,我们需要获得披萨清单。 在将比萨饼添加到购物车之前,我们需要选择一个比萨饼。 因此,我们可以说这三个步骤相互依赖。 在完成前一件事之前,我们无法做一件事。

But if we look at it more broadly, we find that selecting a pizza doesn’t depend on selecting a drink, so we can select them in parallel. That is one thing that machines can do better than we can.

但是,如果从更广泛的角度来看,我们发现选择披萨并不取决于选择饮料,因此我们可以并行选择它们。 这是机器可以做得比我们更好的一件事。

Thus we have discovered some statements which depend on the execution of other statements and some which do not.

因此,我们发现了一些依赖于其他语句执行的语句,而另一些则不依赖于其他语句的执行。

异步函数中与组相关的语句 (Group-dependent statements in async functions)

As we saw, selecting pizza involves dependent statements like getting the list of pizzas, choosing one, and then adding the chosen pizza to the cart. We should group these statements in an async function. This way we get two async functions, selectPizza() and selectDrink() .

如我们所见,选择比萨饼涉及一些相关语句,例如获取比萨饼列表,选择一个比萨饼,然后将所选的比萨饼添加到购物车中。 我们应该将这些语句分组到一个异步函数中。 这样,我们得到两个异步函数, selectPizza()selectDrink()

同时执行这些异步功能 (Execute these async functions concurrently)

We then take advantage of the event loop to run these async non blocking functions concurrently. Two common patterns of doing this is returning promises early and the Promise.all method.

然后,我们利用事件循环来同时运行这些异步非阻塞函数。 两种常见的执行方法是尽早返回 PromisePromise.all方法

让我们修复示例 (Let’s fix the examples)

Following the three steps, let’s apply them on our examples.

按照这三个步骤,让我们将其应用于示例。

async function selectPizza() {
  const pizzaData = await getPizzaData()    // async call
  const chosenPizza = choosePizza()    // sync call
  await addPizzaToCart(chosenPizza)    // async call
}

async function selectDrink() {
  const drinkData = await getDrinkData()    // async call
  const chosenDrink = chooseDrink()    // sync call
  await addDrinkToCart(chosenDrink)    // async call
}

(async () => {
  const pizzaPromise = selectPizza()
  const drinkPromise = selectDrink()
  await pizzaPromise
  await drinkPromise
  orderItems()    // async call
})()

// Although I prefer it this way 

Promise.all([selectPizza(), selectDrink()]).then(orderItems)   // async call

Now we have grouped the statements into two functions. Inside the function, each statement depends on the execution of the previous one. Then we concurrently execute both the functions selectPizza() and selectDrink() .

现在,我们将语句分为两个功能。 在函数内部,每条语句取决于前一条的执行。 然后,我们同时执行selectPizza()selectDrink()函数。

In the second example, we need to deal with an unknown number of promises. Dealing with this situation is super easy: we just create an array and push the promises in it. Then using Promise.all() we concurrently wait for all the promises to resolve.

在第二个示例中,我们需要处理数量未知的promise。 处理这种情况非常容易:我们只需创建一个数组,然后将诺言推入其中即可。 然后,使用Promise.all()并发地等待所有诺言得以解决。

async function orderItems() {
  const items = await getCartItems()    // async call
  const noOfItems = items.length
  const promises = []
  for(var i = 0; i < noOfItems; i++) {
    const orderPromise = sendRequest(items[i])    // async call
    promises.push(orderPromise)    // sync call
  }
  await Promise.all(promises)    // async call
}

// Although I prefer it this way 

async function orderItems() {
  const items = await getCartItems()    // async call
  const promises = items.map((item) => sendRequest(item))
  await Promise.all(promises)    // async call
}

I hope this article helped you see beyond the basics of async/await, and also helped you improve the performance of your application.

我希望本文可以帮助您了解异步/等待的基础知识,也可以帮助您提高应用程序的性能。

If you liked the article, please clap your heart out. Tip — You can clap 50 times!

如果您喜欢这篇文章,请鼓掌。 提示—您可以拍手50次!

Please also share on Fb and Twitter. If you’d like to get updates, follow me on Twitter and Medium or subscribe to my newsletter! If anything is not clear or you want to point out something, please comment down below.

也请在Fb和Twitter上分享。 如果您想获取更新,请在TwitterMedium上关注我,或订阅我的新闻 ! 如果有任何不清楚的地方,或者您想指出点什么,请在下方留言。

翻译自: https://www.freecodecamp.org/news/avoiding-the-async-await-hell-c77a0fb71c4c/

异步回调地狱

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值