Promises

What are promises? This lesson will cover the basics to get started using them.

JavaScript work synchronously which means that each block of code will be executed after the previous one.

const data = fetch('your-api-url-goes-here');
console.log('Finished');
console.log(data);

In the example above, we are using fetch to retrieve data from a url (in this example we are only pretending to be doing so).

In case of synchronous code we would expect the subsequent line to be called only after the fetch has been completed. But in reality, what’s going to happen is that fetch will be called, and straight away the subsequent two console.log will also be called, resulting in the last one console.log(data) to return undefined.

This happens because fetch performs asynchronously, which means that the code won’t stop running once it hits that line but, instead, will continue executing.

What we need is a way of waiting until fetch returns us something before we continue executing our code.

To avoid this we would use callbacks or promises.

 

Callback hell #

You may have heard of something called callback hell, which is something that happens when we try to write asynchronous code as if it were synchronous, meaning that we try to chain each block of code after the other.

In simple words it would something like:

do A, If A do B, if B do C and so on and so forth.

The following is an example just to showcase the meaning of callback hell. Imagine each step is asynchronous so that we would need to send a request to our server for each step of preparing the pizza. Then we need to wait for the server to respond.

Get hands-on with 1400+ tech skills courses.