DEV Community

Cover image for Sync and Async for dummies or cooking chefs
Luiz Calaça
Luiz Calaça

Posted on

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");
}
Enter fullscreen mode Exit fullscreen mode

And now we can cook our doCake() function

const doCake = async () => {
  await doLayer();
  await doSweet();
  await doLayer();
  await doSweet();
  finishRoofCake();
}
Enter fullscreen mode Exit fullscreen mode

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.js

const 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"
*/
Enter fullscreen mode Exit fullscreen mode

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: luizcalaca@gmail.com
Instagram: https://www.instagram.com/luizcalaca
Linkedin: https://www.linkedin.com/in/luizcalaca/
Twitter: https://twitter.com/luizcalaca

Discussion (0)