This content originally appeared on DEV Community and was authored by Luiz Calaça
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!
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.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"
*/
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
This content originally appeared on DEV Community and was authored by Luiz Calaça
Luiz Calaça | Sciencx (2022-01-09T19:57:11+00:00) Sync and Async for dummies or cooking chefs. Retrieved from https://www.scien.cx/2022/01/09/sync-and-async-for-dummies-or-cooking-chefs/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.