I wanted to clearly present async and promises since the concepts were hard for me to understand at first. Here’s my attempt:
Asynchronous requests solve this problem. Instead of waiting for each function to finish, the action is passed to a thread outside of JS. When the request is fulfilled, it’s added to the end of the thread and the callback function will fire. So in our table example, once you spin the top, you can move onto the next table and flip the coin. When the top stops spinning, the table will get shifted to the end of the queue and be ready once you reach the end of the tables.
This ties into promises. A promise is essentially an object that represents an action that hasn’t finished yet but will finish at some point down the road. This makes it easier to handle multiple async requests. When the promise has resolved, we can use the .then function to do something with the returned data. This also makes it easier to chain .then requests together. For example, if we make a request to a server for a token, we want to wait for the token to come back. Once we receive the token, we parse it, and finally do something with that data.
Another example would be if we had an application that is making three separate API requests. Say one API request is for an image, another for the comments, and another for the user data. But we want to wait for all the data to come back before we update the UI so we can use a promise to wait for all the data to finish and then display it to the user. We can use .all to accomplish this with promises.
As a final example below to illustrate promises, we see that A will fire first. Then a fetch request is fired where we wait for a promise from C and then for D. In the meantime, B is fired while we wait. Once C resolves, it fires, then finally D resolves and it fires.<-- Back to blog list