DEV Community

Discussion on: Illustrated JS: JavaScript asynchronous behaviour

Collapse
 
ephraimdavid22 profile image
Agbeze_Obinna

Ma'am, i think Javascript is synchronous by 'default! which means "the Baker needs to finish the baking before moving to icing..that is to say;

// this code would run synchronously
// printing in orderly form
console.log('printing one')
console.log('printing two')

We introduce asynchronous operations into the game when working with APIs as you said.. which means the code below would run asynchronously.
lets use asynchronous function setTimeOut() to simulate a delay comparable to the delays when trying to fetch a data via an API

console.log('printing one')

setTimeout(() => {
    console.log('time up')
}, 2000)

console.log('printing two')

When the code above runs, the two console.log() calls would print first, then the setTimeOut(). This is because by passing a callback function into setTimeOut() we are making the request asynchronous. NB: callback functions typical makes our code asynchronous.

Collapse
 
marinafroes profile image
Marina Costa

Hey Agbeze, thank you for your contribution. :D
In the example above, I can start preparing the icing while I bake the cake because I'm using a promise, as I made a brief reference at the end of the article. In the next article, I explain a little more about promise and I'm writing one that talks about the event loop and setTimeout. I think it will be clearer this way.
Anyway, to make it clearer, I made the following edition in the text:

In fact, JavaScript is asynchronous, and in our cake example, the baker is able to start making the icing while they wait for the cake to be baked.

To:

In fact, JavaScript has some resources that allows us to make it asynchronous, and in our cake example, the baker is able to start making the icing while they wait for the cake to be baked.