Header Ads

Header ADS

JS : async code part1


Hey there, today is hot topic. And it’s crucial to know.

Js by nature is asynchronous language let’s understand how can we unlock the full potential of.

Meaning:

In a Nutshell, ‘start something now and finish it later’. I know it’s not the formal one but I tried to simplify as much as possible.😋

Example of this is when we request data from database:

So we return to finish the work 😃

Simple code :

console.log(1)

setTimeout(()=>console.log(2),3000)

console.log(3)

console.log(4)

 

And the result: 1,3,4,2

The setTimeout is to stimulate an action that takes time.

Let’s take the example of handling request. by using:

https://jsonplaceholder.typicode.com/

const fetch = require('node-fetch')

fetch("https://jsonplaceholder.typicode.com/todos/",{

     method:'GET'

})

.then(response => response.json())

.then(json => console.log(json))

.catch(err=>console.log(err))

 

The first is the url, then we specify the method (GET)

Fetching data requires time. So asynchronous will come to the rescue.   

.Then will fire a function when the previous one will be resolved. And it will take the result (response) as a parameter. We can name it whatever we want. The second then is because we used .json which is also asynchronous.

We can chain as much as we want.

The last one is a catch. It will be fired in case of error in fetching data. It will –of course- take the error in parameter.

Other interesting concept is the promises. As it clear from their name they work the same as. It will take a time some to do and will take two outcomes: resolved (worked) or rejected (failed)

const doSomething=()=>{

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

        //fetch something

        resolve('some data');

        reject('some error');

    }) ;

}

 

doSomething()

       .then(data=>console.log(data))

        .catch(err=>console.log(err))

 

The resolve and reject are built in function. We pass the data from the fetching or the error if it was.  I didn’t do a real fetching so I will pass a dummy data. Of course we can launch only one function (resolve or reject) using a condition.

And you can guess the result 😂.

Hope you like it .Next article we will other interesting things

 

 

 

 

 

No comments

Theme images by enot-poloskun. Powered by Blogger.