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.