Promises are one the most important part in async programming and help to avoid the 'callback hell'.
Promises are used to handle async action like expecting for a result from a server. Promises help to then help to the response using the .then() function. And if something goes wrong then they help to catch the error using the .catch() function.
For example:
In the example below we fetching some data from a server. We use the fetch api which returns us a promise then we can take the response using the .then() function and then we convert it to json using .json(). And because the .json() gives us another promise , we use the .then() again to finally display the response on the console. We also keep a .catch() to catch any errors.
Code :
fetch('https://api.spotify.com/v1/artists/{id}/top-tracks')
.then(response => response.json())
.then(response =>console.log(response))
.catch(err =>console.error(err))
Top comments (0)