Promises

As we saw with the previous fetch example, we utilized something called a promise. A simple way to think of a promise is a value that we are going to want in the future, and what is returned to us is a contract that states I will hand it to you later. Promises were based on the concept of callbacks. If we look at an example of a callback that we could have wrapped around XMLHttpRequest, we can see how it functions as a promise:

const makeRequest = function(loc, success, failure) {
const oldReq = new XMLHttpRequest();
oldReq.addEventListener('load', function(ev) {
if( ev.target.status === 200 ) {
success(ev.target.response);
} else {
failure(ev.target.response);
}
}, { once : true });
oldReq.open('GET', loc);
oldReq.setRequestHeader('Accept', 'application/json');
oldReq.responseType = 'json';
oldReq.send();
}

With this, we get almost the same functionality that we have with a promise but utilizing callbacks or functions that we want to run when something happens. The problem with a callback system is something known as callback hell. This is the idea that highly asynchronous code will always have callbacks and this means that if we want to utilize it, we will have a wonderful tree view of callbacks. This would look like the following:

const fakeFetchRequest(url, (res) => {
res.json((final) => {
document.querySelector('#content').innerHTML =
JSON.stringify(final);
});
});

This fake version of fetch would be if the API for fetch were not promise-based. First, we would pass in our URL. We would also need to provide a callback for when our response comes back in. We would then need to pass that response to the json method that would also need a callback to turn the response data into json. Finally, we would have the result and would put it into our DOM.

As we can see, callbacks can lead to quite a few problems. Instead, we have the promise. A promise takes a single argument when it is created, a function that has two parameters—resolve and reject. With these, we can either give a success back to our caller through the resolve function, or we can error out with the reject function. This, in turn, will allow us to chain these promises together through then calls and the catch call, as we can see in our fetch example.

However, these can also lead to another problem. We can get a giant chain of promises that looks a bit better than callbacks, but not by much. We then get the async/await system. Instead of constantly chaining promises with then, we can use await to utilize the response. We can then turn our fetch call into something that looks like the following:

(async function() {
const res = await fetch('http://localhost:8081/sample');
const final = await res.json();
document.querySelector('#content').innerHTML = JSON.stringify(final);
})();

The async descriptor before the function tells us that this is an async function. We cannot utilize await if we do not have this. Next, instead of chaining then functions together, we can just await the function. The result is what would have been wrapped in our resolve function. Now, we have something that reads quite well.

We do need to be careful with the async/await system. It does actually wait, so if we put this on the main thread or do not have this wrapped in something, it can block the main thread, causing us to lock up. Also, if we have a bunch of tasks that we want to run at the same time, instead of awaiting them one at a time (making our code sequential), we can utilize Promise.all(). This allows us to put a bunch of promises together and allows them all to run asynchronously. Once they all return, we can continue execution.

One nice thing about the async/await system is that it can actually be faster than using generic promises. Many browsers have added optimizations around these specific keywords and so we should try to use them at every opportunity we have.

It has been stated before, but browser vendors are constantly making improvements to their implementations of the ECMAScript standard. This means that new technologies will be slow at first, but once they are in widespread use or they are agreed upon by all vendors, they will start to optimize and usually make them faster than their counterparts. When possible, utilize the newer technologies that browser vendors are giving us!
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.199.162