How to use Promise using then & catch(Simplified)

We’ll see a simple example of consuming Promise object using then & catch block to handle an async request.

The method init() is the startup method and when this init() method is called, it calls the getUsers() method.

Let’s how we are consuming Promise here to handle async call.

Here, we are handling an async call in Promise like code using .then() and .catch()
 
In then() block we get the output of async calls the getUsers() method which has an awaitable method inside it.
 
So the .then() {} block after the getUsers() method waits for the output of getUsers() method.
We get the dummy user data as output in the then() block if there are not error; otherwise if there are some error then we get response in the .catch() block.
 
 
 async function getUsers(){
    document.body.innerHTML = 'making getUsers call.....'

    var users  = await fetch('https://jsonplaceholder.typicode.com/users/1')
    const data = await users.json();
    return data;
}

function init(){
     getUsers()                 
        .then(res =>{
        document.body.innerHTML = res.name
        })
        .catch(err =>{
            document.body.innerHTML = 'some error'
        })
}
init();


This whole script can be used in an file directly to see how it works.

html body -->
<body>
    <script src="asyncToPromise.js">
</body>

Leave a Reply

Your email address will not be published. Required fields are marked *