DEV Community

loading...
Cover image for Learn callbacks, promises, Async/Await by Making Ice Cream 🍧🍨🍦

Learn callbacks, promises, Async/Await by Making Ice Cream 🍧🍨🍦

Joy Shaheb
Front end Developer πŸ”₯ || Youtuber 🎬|| Blogger ✍|| K-pop fan ❀️️based in Dhaka, Bangladesh.
Originally published at freecodecamp.org ・Updated on ・14 min read

Today we're gonna run an ice cream shop and learn asynchronous JS. Along the way, we'll understand how to use

  • Callbacks
  • Promises
  • Async / Await

Alt Text

Table of Contents -

  • What's Asynchronous JavaScript
  • Synchronous Vs Asynchronous JavaScript
  • Callbacks
  • Promises
  • Async / Await
  • Conclusion

You can watch this tutorial on YouTube as well if you like

What's Asynchronous JavaScript ?

Alt Text

If you want to efficiently build projects, Then this is for you.

The theory of async javascript helps you to break down complex & big project into smaller tasks.

And then, using any 1 of these 3 techniques (callbacks, promises or Async/await) we are running those small tasks in a way that we get the final result

Let's Dive in !πŸŽ–οΈ

Synchronous VS Asynchronous ->

Alt Text

Synchronous System

In this system, tasks are completed 1 after another.

Think of this like, you have just 1 hand to accomplish 10 tasks. So, you have to complete 1 task at a time.

Take a look at the GIF πŸ‘‡

Synchronous System

You can notice that, without loading the 1st image completely, the 2nd image doesn't load.

Note :

By default JavaScript is Synchronous [single threaded] Think like this, 1 thread means 1 hand

Asynchronous System

In this system, tasks are completed independently.

Here, Imagine that For 10 tasks, you're given 10 hands. So, each hand can do the task independently.

Take a look at the GIF πŸ‘‡

Asynchronous System

You can notice that, All the images are loading on their own pace. Nobody is waiting for anybody.

To summarize -

When 3 images are on a marathon, in ->

  • Synchronous : 3 images are on the same lane. Overtaking the other is not allowed. The race is finished one by one. If image number 3 stops, everyone stops.

Alt Text

  • Asynchronous: 3 images are on different Lanes. They'll finish the race on their own pace. Nobody stops for anybody

Alt Text

Examples

Alt Text

Before starting our project, Let's look at examples and clear our doubts.

Synchronous

Alt Text

To test The synchronous system, Write these on JavaScript

console.log(" I ");

console.log(" eat ");

console.log(" Ice Cream ");
Enter fullscreen mode Exit fullscreen mode

The result on console πŸ‘‡

Alt Text

Asynchronous

Alt Text

Let's say it takes 2 seconds to eat ice cream,
Now, let's test The Asynchronous system, Write these on JavaScript.

Note : Don't worry, we'll discuss setTimeout() function in this article.

console.log("I");

// This will be shown after 2 seconds

setTimeout(()=>{
  console.log("eat");
},2000)

console.log("Ice Cream")
Enter fullscreen mode Exit fullscreen mode

The result on console πŸ‘‡

Alt Text

Setup

Alt Text

  • For This project you can just open Codepen.io and start coding. Or, you can do it on VS code.

  • Open The JavaScript section

  • Once done, open your Developer console window. We'll write code and see the results on the console.

What are Callbacks?

Alt Text

Nesting a function inside another function as an argument are called callbacks.

An illustration of callback ->

Alt Text

Note : Don't worry, Examples are coming.

Why do we use callbacks?

When doing a complex task, we break that task down into small steps. To establish relationship between these steps according to time(Optional) & order, we use callbacks.

Take a look at this πŸ‘‡

Alt Text

These are the small steps needed to make ice cream. Also note, order of the steps and timing are crucial. You can't just chop the fruit and serve ice cream.

At the same time, if previous step is not completed, we can't move to the next step.

Alt Text

To explain that in more details, let's start our ice cream shop business

But Wait....

Alt Text

We're gonna have 2 sides.

  • The store room will have ingredients [Our Backend]
  • We'll produce ice cream on our kitchen [The frontend]

Alt Text

Let's store our data

Now, we're gonna store our ingredients inside an object. Let's start !

Alt Text

store ingredients inside objects Like this πŸ‘‡

let stocks = {
    Fruits : ["strawberry", "grapes", "banana", "apple"]
 }
Enter fullscreen mode Exit fullscreen mode

Our other ingredients are here πŸ‘‡

Alt Text

Store them in JavaScript Object like this πŸ‘‡

let stocks = {
    Fruits : ["strawberry", "grapes", "banana", "apple"],
    liquid : ["water", "ice"],
    holder : ["cone", "cup", "stick"],
    toppings : ["chocolate", "peanuts"],
 };
Enter fullscreen mode Exit fullscreen mode

The entire business depends on the order of our customers. Then, starts production and then we serve ice cream. So, we'll create 2 functions ->

  • order
  • production

Alt Text

See this illustration πŸ‘‡

Alt Text

Let's make our functions.

Note : We'll use arrow functions

let order = () =>{};

let production = () =>{};
Enter fullscreen mode Exit fullscreen mode

Now, Let's establish relationship between these 2 functions using a callback. see this πŸ‘‡

let order = (call_production) =>{

  call_production();
};

let production = () =>{};
Enter fullscreen mode Exit fullscreen mode

Let's do a small test

we'll use the console.log() function to conduct tests to clear our doubts regarding how we established the relationship between the 2 functions.

let order = (call_production) =>{

console.log("Order placed. Please call production")

// function πŸ‘‡ is being called 
  call_production();
};

let production = () =>{

console.log("Production has started")

};
Enter fullscreen mode Exit fullscreen mode

To run the test, we'll call the order function. And we'll place the 2nd function named production as it's argument.

// name πŸ‘‡ of our second function
order(production);
Enter fullscreen mode Exit fullscreen mode

The result on our console πŸ‘‡

Alt Text

Take a break

So far so good, Take a break !

Alt Text

Clear our console.log

Keep these code and remove everything [don't delete our stocks variable]. On our 1st function, pass another argument so that we can receive the order [Fruit name]

// Function 1

let order = (fruit_name, call_production) =>{

  call_production();
};

// Function 2

let production = () =>{};


// Trigger πŸ‘‡

order("", production);
Enter fullscreen mode Exit fullscreen mode

Here's Our steps, and time each step will take to execute.

Alt Text

to establish the timing part, The function setTimeout() is excellent as it is also uses a callback by taking a function as an argument.

Alt Text

Now, Let's select our Fruit.

// 1st Function

let order = (fruit_name, call_production) =>{

  setTimeout(function(){

    console.log(`${stocks.Fruits[fruit_name]} was selected`)

// Order placed. Call production to start
   call_production();
  },2000)
};

// 2nd Function

let production = () =>{
  // blank for now
};

// Trigger πŸ‘‡
order(0, production);
Enter fullscreen mode Exit fullscreen mode

The result on our console πŸ‘‡

Note: Result displayed after 2 seconds.

Alt Text

If you're wondering how we picked the strawberry from our stock variable. Here's the code with format πŸ‘‡

Alt Text

Don't delete anything. start writing on our production function.
Write these πŸ‘‡

Note: We'll use arrow functions.

let production = () =>{

  setTimeout(()=>{
    console.log("production has started")
  },0000)

};
Enter fullscreen mode Exit fullscreen mode

The result πŸ‘‡

Alt Text

we'll nest another setTimeout function in our existing setTimeout function to chop the fruit. Like this πŸ‘‡

let production = () =>{

  setTimeout(()=>{
    console.log("production has started")


    setTimeout(()=>{
      console.log("The fruit has been chopped")
    },2000)


  },0000)
};
Enter fullscreen mode Exit fullscreen mode

The result πŸ‘‡

Alt Text

If you remember, this is the list of our steps.

Alt Text

Let's complete our ice cream production by nesting a function inside another [Also known as Callbacks ]

let production = () =>{

  setTimeout(()=>{
    console.log("production has started")
    setTimeout(()=>{
      console.log("The fruit has been chopped")
      setTimeout(()=>{
        console.log(`${stocks.liquid[0]} and ${stocks.liquid[1]} Added`)
        setTimeout(()=>{
          console.log("start the machine")
          setTimeout(()=>{
            console.log(`Ice cream placed on ${stocks.holder[1]}`)
            setTimeout(()=>{
              console.log(`${stocks.toppings[0]} as toppings`)
              setTimeout(()=>{
                console.log("serve Ice cream")
              },2000)
            },3000)
          },2000)
        },1000)
      },1000)
    },2000)
  },0000)

};
Enter fullscreen mode Exit fullscreen mode

Our result on console πŸ‘‡

Alt Text

Feeling confused ?

Alt Text

This is called a callback hell. It looks something like this πŸ‘‡

Alt Text

What's the solution to this?

Promises

Alt Text

This was invented to solve the callback hell problem and to better handle our tasks.

Take a break

But first, Take a break !

Alt Text

This is how a promise looks like.

Alt Text

Let's Dissect Promises together !

Alt Text

Alt Text

There're 3 states of a promise

  • Pending : This is the initial stage. Nothing happens here. Think like this, your customer is taking his time to give an order. But, hasn't ordered anything.
  • Resolve : This means that your customer has received his food and is happy.
  • Reject : This means that your customer didn't receive his order and left the restaurant.

Let's adopt promises to our ice cream production.

But wait......

Alt Text

We need to understand 4 more things ->

  • Relationship between time & work
  • Promise chaining
  • Error handling
  • .finally handler

Let's start our ice cream shop and understand them one by one by taking small baby steps.

Relationship of time & work

If you remember, these are our steps & time each takes to make ice cream.

Alt Text

For this to happen, Let's create a variable in JavaScript πŸ‘‡

let is_shop_open = true;
Enter fullscreen mode Exit fullscreen mode

now create a function named [ order ] and pass 2 arguments named [ work, time ]

let order = ( time, work ) =>{

  }
Enter fullscreen mode Exit fullscreen mode

Now, we're gonna make a promise to our customer, "We will serve you ice-cream" Like this ->

let order = ( time, work ) =>{

  return new Promise( ( resolve, reject )=>{ } )

  }
Enter fullscreen mode Exit fullscreen mode

Note : Our promise has 2 parts ->

  • Resolve [ ice cream delivered ]
  • Reject [ customer didn't get ice cream ]
let order = ( time, work ) => {

  return new Promise( ( resolve, reject )=>{

    if( is_shop_open ){

      resolve( )

    }

    else{

      reject( console.log("Our shop is closed") )

    }

  })
}
Enter fullscreen mode Exit fullscreen mode

Alt Text

Let's add the time & work factor inside our Promise using a [ setTimeout() ] function inside our [ if statement ]. Follow me πŸ‘‡

Note : In real life, you can avoid the time factor as well. This is completely dependent on the nature of your work.

let order = ( time, work ) => {

  return new Promise( ( resolve, reject )=>{

    if( is_shop_open ){

      setTimeout(()=>{

       // work is πŸ‘‡ getting done here
        resolve( work() )

// Setting πŸ‘‡ time here for 1 work
       }, time)

    }

    else{
      reject( console.log("Our shop is closed") )
    }

  })
}
Enter fullscreen mode Exit fullscreen mode

Now, we're gonna use our newly created function to start ice-cream production. Let's start !

// Set πŸ‘‡ time here
order( 2000, ()=>console.log(`${stocks.Fruits[0]} was selected`))
//    pass a ☝️ function here to start working
Enter fullscreen mode Exit fullscreen mode

The result πŸ‘‡ after 2 seconds

Alt Text

good job !

Alt Text

Promise chaining

In this method, we are defining what to do when 1st task is complete using the [ .then handler ]. It looks something like this πŸ‘‡

Alt Text

The [ .then handler ] returns a promise when our original promise was resolved.

Example :

Alt Text

Let me make it more simple, It's similar to giving instruction to someone. You're telling someone to " First do This, Then do this, then this, then...., then...., then...., etc.

  • The first task is our [ original ] promise.
  • The rest are returning our promise once 1 small work is completed

Let's implement this on our project. At the bottom write these. πŸ‘‡

Note : don't forget to write the [ return ] word inside our [ .then handler ] Otherwise, it won't work properly. If you're curious, try removing the [ return ] word once we finish the steps

order(2000,()=>console.log(`${stocks.Fruits[0]} was selected`))

.then(()=>{
  return order(0000,()=>console.log('production has started'))
})
Enter fullscreen mode Exit fullscreen mode

The result πŸ‘‡

Alt Text

using the same system, let's finish our project πŸ‘‡

// step 1
order(2000,()=>console.log(`${stocks.Fruits[0]} was selected`))

// step 2
.then(()=>{
  return order(0000,()=>console.log('production has started'))
})

// step 3
.then(()=>{
  return order(2000, ()=>console.log("Fruit has been chopped"))
})

// step 4
.then(()=>{
  return order(1000, ()=>console.log(`${stocks.liquid[0]} and ${stocks.liquid[1]} added`))
})

// step 5
.then(()=>{
  return order(1000, ()=>console.log("start the machine"))
})

// step 6
.then(()=>{
  return order(2000, ()=>console.log(`ice cream placed on ${stocks.holder[1]}`))
})

// step 7
.then(()=>{
  return order(3000, ()=>console.log(`${stocks.toppings[0]} as toppings`))
})

// Step 8
.then(()=>{
  return order(2000, ()=>console.log("Serve Ice Cream"))
})
Enter fullscreen mode Exit fullscreen mode

The result πŸ‘‡

Alt Text

Error handling

This is used to handle our errors when something goes unexpected. But first, understand the promise cycle

Alt Text

Alt Text

To catch our error, let's change our variable to false.

let is_shop_open = false;
Enter fullscreen mode Exit fullscreen mode

Which means our shop is closed. We're not selling ice cream to our customers.

To handle this, we use the [ .catch handler] . Just like the [ .then handler ], It also returns a promise, only when our original promise is rejected.

A small reminder here -

  • [.then] works when promise is resolved
  • [.catch] works when promise is rejected

come at the very bottom and write πŸ‘‡

Note : There should be nothing between your previous .then handler and the .catch handler

.catch(()=>{
  console.log("Customer left")
})
Enter fullscreen mode Exit fullscreen mode

The result πŸ‘‡

Alt Text

Note :

  • 1st message is coming from the reject() part of our promise
  • 2nd message is coming from .catch handler

.finally() handler

Alt Text

There's something called the finally handler which works regardless whether our promise was resolved or rejected.

For an example : Serve 0 customer or 100 customers, Our shop will close at the end of the day

If you're curious to test this, come at very bottom and write these πŸ‘‡

.finally(()=>{
  console.log("end of day")
})
Enter fullscreen mode Exit fullscreen mode

The result πŸ‘‡

Alt Text

Everyone ! Please welcome Async / Await !

Async / Await

Alt Text

This is Claimed to be the better way to write promises and helps to keep our code simple & clean.

All you have to do is, write the word [ async ] before any regular function and it becomes a promise.

But first, Take a break

Alt Text

Let's have a look πŸ‘‡

Alt Text

Before

To make a promise we wrote

function order(){
   return new Promise( (resolve, reject) =>{

    // Write code here
   } )
}
Enter fullscreen mode Exit fullscreen mode

Now [ using Async / Await ]

In Async / Await method, we make promise like this πŸ‘‡

//πŸ‘‡ the magical keyword
 async function order() {
    // Write code here
 }
Enter fullscreen mode Exit fullscreen mode

But wait......

Alt Text

You need to understand ->

  • try, catch usage
  • How to use the Await keyword

Try, Catch usage

[ Try ] keyword is used to run our code [ catch ] is used to catch our errors. It's the same concept as of the one we saw on promises.

Let's see a comparison

Note : We'll see a small demo of the format, then we'll start coding

Promises -> Resolve, reject

We used resolve & reject in promises like this ->

function kitchen(){

  return new Promise ((resolve, reject)=>{
    if(true){
       resolve("promise is fulfilled")
    }

    else{
        reject("error caught here")
    }
  })
}

kitchen()  // run the code
.then()    // next step
.then()    // next step
.catch()   // error caught here
.finally() // end of the promise [optional]
Enter fullscreen mode Exit fullscreen mode

Async / Await -> try, catch

Here we work like this format

//πŸ‘‡ Magical keyword
async function kitchen(){

   try{
// Let's create a fake problem      
      await abc;
   }

   catch(error){
      console.log("abc does not exist", error)
   }

   finally{
      console.log("Runs code anyways")
   }
}

kitchen()  // run the code
Enter fullscreen mode Exit fullscreen mode

Note : don't panic, we'll discuss about the [await keyword] next

you can notice, the difference between promises, Async / Await

The Await keyword usage

Alt Text

The keyword [ await ] makes JavaScript wait until that promise settles and returns its result.

A practical example

We don't know which topping customer prefers, Chocolate or peanuts?
We need to stop our machine, go and ask our customer, "Sir, which topping would you love ?"

Notice here, only Our kitchen is stopped, but our staff outside the kitchen will still work like

  • doing the dishes
  • cleaning the tables
  • taking orders, etc.

A Code Example

Alt Text

Let's create a small promise, to ask which topping to use. The process takes 3 seconds.

function toppings_choice (){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{

      resolve( console.log("which topping would you love?") )

    },3000)
  })
}
Enter fullscreen mode Exit fullscreen mode

now, let's create our kitchen function with the async keyword at first.

async function kitchen(){

  console.log("A")
  console.log("B")
  console.log("C")

  await toppings_choice()

  console.log("D")
  console.log("E")

}

// Trigger the function

kitchen();
Enter fullscreen mode Exit fullscreen mode

Let's add other works below the kitchen() call.

console.log("doing the dishes")
console.log("cleaning the tables")
console.log("taking orders")
Enter fullscreen mode Exit fullscreen mode

The result

Alt Text

We are literally going outside our kitchen to ask our customer, "what is your toppings choice?" In the mean time, other works are done.

Once, we get the toppings choice, we enter the kitchen and finish the job.

Small note

When using Async/ Await, you can also use the [ .then, .catch, .finally ] handlers as well which are a core part of promises.

Let's Open our Ice cream shop Again

Alt Text

We're gonna create 2 functions ->

  • kitchen : to make ice cream
  • time : assigning amount of time each small task will need to accomplish.

Let's start ! First, create the time function ->

let is_shop_open = true;

function time(ms) {

   return new Promise( (resolve, reject) => {

      if(is_shop_open){
         setTimeout(resolve,ms);
      }

      else{
         reject(console.log("Shop is closed"))
      }
    });
}

Enter fullscreen mode Exit fullscreen mode

Now, Let's create our kitchen ->

async function kitchen(){
   try{

     // instruction here
   }

   catch(error){
    // error management here
   }
}

// Trigger
kitchen();
Enter fullscreen mode Exit fullscreen mode

Let's give small instructions and test if our kitchen function is working or not

async function kitchen(){
   try{

// time taken to perform this 1 task
     await time(2000)
     console.log(`${stocks.Fruits[0]} was selected`)
   }

   catch(error){
     console.log("Customer left", error)
   }

   finally{
      console.log("Day ended, shop closed")
    }
}

// Trigger
kitchen();
Enter fullscreen mode Exit fullscreen mode

The result, When shop is open πŸ‘‡

Alt Text

The result when shop is closed πŸ‘‡

Alt Text

So far so good !

Alt Text

Let's complete our project.

Here's the list of our task again πŸ‘‡

Alt Text

first, open our shop

let is_shop_open = true;
Enter fullscreen mode Exit fullscreen mode

Now write the steps inside our kitchen() function following the steps πŸ‘‡

async function kitchen(){
    try{
    await time(2000)
    console.log(`${stocks.Fruits[0]} was selected`)

    await time(0000)
    console.log("production has started")

    await time(2000)
    console.log("fruit has been chopped")

    await time(1000)
    console.log(`${stocks.liquid[0]} and ${stocks.liquid[1]} added`)

    await time(1000)
    console.log("start the machine")

    await time(2000)
    console.log(`ice cream placed on ${stocks.holder[1]}`)

    await time(3000)
    console.log(`${stocks.toppings[0]} as toppings`)

    await time(2000)
    console.log("Serve Ice Cream")
    }

    catch(error){
     console.log("customer left")
    }
}
Enter fullscreen mode Exit fullscreen mode

The result πŸ‘‡

Alt Text

Conclusion

Here's Your Medal For reading till the end ❀️

Suggestions & Criticisms Are Highly Appreciated ❀️

Alt Text

Credits -

Discussion (22)

Collapse
rolfst profile image
Rolf Strijdhorst

Why is everyone confusing asynchronisity with parallelism?
What you describe is parallelism. Async means: the call doesn't complete right away. This can be handled using the eventloop (v8 or something simular) or threads (Java et. al). the loading of images is asynchronous because of latency not because of the runtime.
And following one after another is sequentality.
Often these things can be used interchangeably but not in your examples.
You describe parallelism mostly. One of the key enablers is promise.all() which executes in parallel. An ajax (xhr) request is async and the runtime itself waits on the eventloop to finish this is what promise.all does it waits till all calls are resolved and then continues.

This also makes the async/await confusing since you're making the execution look like a synchronous/sequentual execution while it actually is not.
(I know that was the purpose of the developers though, to make it look synchronous)

Collapse
slikts profile image
Reinis Ivanovs

As unkind as that may sound, since a lot of work has obviously gone into the article, it should be unpublished or a significant correction added, because it's actively misleading about what an "evented", non-blocking or async i/o concurrency model is.

Collapse
raquelsartwork profile image
Raquel Santos | RS-coding

can you give examples of async JS in real world? I still find Difficult to know when I should use it. Thank you

Collapse
thatanjan profile image
Anjan Shomodder

You can use async js anywhere. But most of the time you will use it for data fetching from third party apis. You don't want to stop other process while fetching data. Because at worst case, fetching data can take long time. If you stop other process, then user might see a blank page or an incomplete page. You will never want that.
So you let other process to finish first, then do the data fetching. I hope that make sense to you.

Happy Coding.

Collapse
raquelsartwork profile image
Raquel Santos | RS-coding

thank you :) can you give me other examples that isn't about fetch data from apis?

Thread Thread
thatanjan profile image
Anjan Shomodder

I don't see much examples.

  1. You might want to use some third party library which is performance heavy. You can make that asynchronous.
  2. If you want to use alert, then you can use async js. Because window alert blocks all the process.

If you are a beginner, then I would recommend you to not to bother this about too much. I also did that. But end of the day, you will use it for data fetching.

Thread Thread
raquelsartwork profile image
Raquel Santos | RS-coding

I am not a beginner :) This is the subject that I always get me confused to apply in real world. If only to fetch data from apis or other cases. thank you for your answer. you have explained well :)

Thread Thread
urielsouza29 profile image
Uriel dos Santos Souza

Oi, sei que vocΓͺ fala portuguΓͺs entΓ£o vou responder na minha lΓ­ngua.
PortuguΓͺs brasileiro.

Se for frontend. Quase tudo de assΓ­ncrono sera para acessar APIs.
Como exemplos:
Mandar algo ser salvo! (via react, ajax, axios ou fetch)
Fazer ediçáes! (via react, ajax, axios ou fetch)
Fazer buscas! (via react, ajax, axios ou fetch)
Esperar por alguma coisa(um ID, um calculo que serΓ‘ feito no banco ou direto no front)

Tudo que se comunique com alguma API vai ter que usar o assincronismo
Hoje praticamente qualquer aplicação minima tem api para acessar!

No back:
Basicamente a mesma coisa
Mandar algo ser salvo no banco de dados
Fazer ediçáes e salvar no banco de dados
Fazer buscas direto no banco de dados!
Fazer cΓ‘lculos, um bom exemplo Γ© fazer encriptagem de senha.
Acessar APIs
Qualquer coisa que leve algum tempo no back devemos usar o assincronismo!
Espero ter ajudado

Thread Thread
raquelsartwork profile image
Raquel Santos | RS-coding

Obrigada! Deu para entender ali acima com autor do texto mas obrigada na mesma pelo esclarecimento mais uma vez . :)

Thread Thread
devzom profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Jacob • Edited

Write in English

Thread Thread
raquelsartwork profile image
Raquel Santos | RS-coding

I said "thank you. I did understand what the author of the post said, but thank you anyway for the explanation again."

Thread Thread
devzom profile image
Jacob

I didn't mean that... :) That was a respond to the thread, to point that we all should use English in international website, it's easier to follow and understand subject. But Thank You :)

Thread Thread
raquelsartwork profile image
Raquel Santos | RS-coding

of course and you are absolutly right. that is why I translated it my part :)

Collapse
longthtran profile image
Long Tran • Edited

You are expected to know the definition of async task, also non-blocking IO (becasue you are JS developers :D ). Here is what I found on stackoverflow: "Point of an async Task is to let it execute in background without locking the main thread, such as doing a DownloadFileAsync".

Most of async task I cope with when coding in JS are: calling API, making a query to database/cache, reading/writing a file,... The reason they are called "async" because you call those functions which are not supposed to return the result "immediately". The moment you call the async task function (lets call func A), your CPU (main thread) is free and it could be used to do another task meanwhile the previous async task function A is in "pending" state waiting for the result to comes back. After then, your JS code shall run to the next line without being blocked at the line you call the async function A; this is not what we want, we expect the code runs sequentially from the top to bottom line by line in case the underneath code must use the result of A ;)

When to use Promise -> When your project is using ES5 or older version, or maybe you are dealing with some library are not written in async/await style.
For ex: a time I played with Google Cloud Storage API written with Promise/callback styles, having some listener method onFinish, onError,... You can wrap their code inside a Promise((resolve, reject) => {}), and your async function return that Promise. From now on, you are freely await your async function!
Sr for the long writing, hope it can help

Collapse
raquelsartwork profile image
Raquel Santos | RS-coding

thanl you so much for the explanation :) always a help

Collapse
thedailycommute profile image
John C

Off-topic, but in response to Jacob's request to Uriel dos Santos Souza and Raquel Santos to write in English, I highly recommend the Deepl translator - deepl.com/translator, and in particular the free (Windows) application.

I am a native English speaker, but also speak (European) Portuguese, and can confirm that the Deepl translator provided a near perfect English translation of Uriel's post (and significantly better than the attempt by Google Translate :-).

Collapse
riorocker97 profile image
ChangNoi

couldn't wrap my head around when i starting learning about this feature a while ago. this is a nice way to educate myself even more. thank you for creating this.

Collapse
codewaseem profile image
codewaseem • Edited

I highly appreciate the effort you have put to write this article.

But it looks like you have totally misunderstood the concept of synchronous vs asynchronous code.

The analogy you used here doesn't fit and I would say it is exact opposite to describe asynchronous code, which explains why you misunderstood the concept yourself in the first place.

Asynchronous code has nothing to do with dividing the task in smaller pieces.

In very basic terms, synchronous code will say "Please WAIT and be on the line while I finish processing your request.
And asynchronous code will say "Thank for calling, I will process your request soon, you DON'T HAVE TO WAIT HERE. You can continue with other tasks and I will call you back once I finish.

You can use callbacks, promises, or async/await and still be synchronous, like in your ice-cream example. You are waiting at every step to finish before continuing on to the other. This is what synchronous is.

Synchronous code is blocking, makes you wait.
Asynchronous code is non-blocking, allows you to move forward with other things.

Asynchronous code doesn't mean that it runs on multiple threads. JavaScript is single-threaded, no matter if you write synchronous or asynchronous code.

Please correct your understanding and update the article at its earliest. Otherwise you will end up misleading other developers.

Thanks. Again, I highly appreciate your work.

Collapse
timhuang profile image
Timothy Huang

Interesting introducing, thank you!

Collapse
3p4r4 profile image
lenin jose mendoza espina

Ey! te felicito tremenda explicaciΓ³n que hasta YO como latino te he comprendido de la mejor manera. Te felicito! sigue asi...

Collapse
mrcodedev profile image
MrCodeDev

πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘