Get a better understanding of async / await through the way you cook ramen

Tram Ho

Object

There is a great deal of knowledge about async / await.

Used to use async / await but not very sure.

For convenience, use async / await in any case!

There will be many ideas that should be, but in fact this is a trick. If you do not pay attention to understand it will bring ineffective feeling. This article will be a testament to that. However, instead of explaining by using the source code, I will refer to how to make Ramen noodles to be more vivid and easy to visualize.

Let’s start cooking ramen!

It’s a little sudden, but you will play the role of a noodle shop owner. Your noodle shop has 3 skilled employees who undertake the following areas:
In charge of noodles. In charge of soup In charge of additives (you probably have seen this format somewhere before).

Next, to create Ramen:

  1. The noodle worker will boil the noodles.
  2. Soup staff will make soup.
  3. Personnel in charge of creating additives for grilling pork and slicing thinly. Here are the necessary steps to complete the ramen.

Let’s prepare the API!

Let’s imagine that we have prepared the following APIs:

End pointEnd pointOverview
/ noodleGETget noodles
/soupGETget Soup
/ porkGETget PG
/ ramenPOSTCreate Ramen

Let’s fight!

Too simple, easy as tangent noodles.

Ok, looks like it’s going to have ramen soon, but with this method, NG .

A await trap

When using await, processes inside the async function will temporarily pause until the Promise result of the specified function returns the result. So that means ???

await axios.get('/noodle');

Will wait for processes until the result of / noodle ‘ returns. During the test, / soup / pork will not be requested. Means: Wait for the boil to finish. The noodles will start to cook the soup. Wait until the soup is ready to start slicing the meat. Something like that will lose its effectiveness while the shop owner like you have to pay for all 3 employees at the same time! So wait until finish all then you can imagine the American will ntn and that.

So the solution here is that it is not necessary to wait for each person to finish to proceed to the next stage, you pay the employees so you want to direct all 3 employees at the same time. work together, independent of anyone.

Specifically how to do it?

Translate timing await.

Done! Cup!

Summary

With the above contents, we are having a hot bowl of ramen that will blow and eat on the cold winter days. But don’t forget:

** Need to wait + wait + where to wait + wait at what time, it’s not necessary then don’t wait anymore **

Share the news now

Source : Viblo