Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 9, 2022 07:57 pm GMT

Sync and Async for dummies or cooking chefs

Hello devs and not devs!

I always guess there is not thing that is so difficult and impossible to learn, but all things it is necessary one important thing: dedication and what the best way for your learning.

Daily analogies is a way that the majority people could learn. So, what we will learn here are sync (synchronous) and async (asynchronous) concepts with: CAKE!

A beautiful and delicious cake

How can we make a cake with many layers?

1 - Do one layer, after the next, and so on,
2 - Clearly you can't do the second without do the first before, right?

Therefore, I need to wait one layer to do the next, got it? Yes? So, you already know the concepts above. When you need to wait something finish first to go to another action, so we are talking about async/await, on the contrary would be the sync.

For each layer of our cake we need to wait one before, but at the final when we are doing the roof cake, it can be done with sync because we don't have a new action.

Let's detail in Javascript and cook our doLayer(), doSweet() and finishRoofCake() functions:

const doLayer = () => {    console.log("do layer");}const doSweet = () => {    console.log("layer for sweet");}const finishRoofCake = () => {    console.log("delicious roof");}

And now we can cook our doCake() function

const doCake = async () => {  await doLayer();  await doSweet();  await doLayer();  await doSweet();  finishRoofCake();}

You can take all this functions and write in one file cake.js and call doCake() at the end and the returns will be:

//cake.jsconst doLayer = () => {    console.log("do layer");}const doSweet = () => {    console.log("layer for sweet");}const finishRoofCake = () => {    console.log("delicious roof");}const doCake = async () => {  await doLayer();  await doSweet();  await doLayer();  await doSweet();  finishRoofCake();}cake();/* output"do layer""layer for sweet""do layer""layer for sweet""delicious roof"*/

You like to cook? Ops, to program? A simple concept help us to grow up rapidly. Learn what the best way to work for your learning and fire!

Contacts
Email: [email protected]
Instagram: https://www.instagram.com/luizcalaca
Linkedin: https://www.linkedin.com/in/luizcalaca/
Twitter: https://twitter.com/luizcalaca


Original Link: https://dev.to/luizcalaca/sync-and-async-for-dummies-or-cooking-chefs-5759

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To