You may have heard of the word synchronous/asynchronous programming. It is an essential knowledge for the front end engineer, but it is pretty complicated to understand, too. That’s why I summarize this topic this time (for my self, too)
The result will be shown like below as you know.
In this way, the program’s code runs straight along line by line without asynchronous programming. By the way, what will be happened if you have a code like below? You can try this code on live, too (push the first button): https://blackstone8960.github.io/article/async/
In this case, element of paragraph will be rendered after 1 billion calculations. I know, this is very unrealistic example. But imagine that your program has an expensive operation which takes a long time like this. The browser can’t continue to handle user input or perform other tasks like rendering something important until this expensive process ends. It is called Blocking, and this can be a big problem for your sites.
<Task A> --> <Task B> --> <Task C> --> <Task D>Multiple thread
Thread 1:<Task A> --> <Task B>
Thread 2:<Task C> --> <Task D>
With using a tool called Web workers, we can realize this process. Following code is an example to use it. To try this code on live, too (push the second button): https://blackstone8960.github.io/article/async/
This is a rewrite of an example that calculates 1 billion times. You will find the rendering will be executed before calculation finishes this time.
Asynchronous programming using promise
We can process the multiple tasks using Web workers, but there are still some problems about it. At first, we can’t manipulate DOM with it. It only calculates numbers, and it can’t update UI. The second problem is that you can’t run the process after multiple processes end. There are some options to solve these problems, but the one of the most simple and manageable method is promise.
Following code is written with promise syntax, and to fetch an image and render it. In this code, even though there is logged sentence between logging ‘Start’ and ’End’, it will logged out at the very last. (Check it on live: https://blackstone8960.github.io/article/async/promise.html).
That’s because the process of loading image is executed asynchronously. There are some methods executed asynchronously, but promise is a good way to handle them.
How to write Promise syntax
When you use promise, you should create the instance of promise object. Following code is description of how to set its constructor.
In the constructor, you can write the function called executor. It should be asynchronous and it has two arguments called resolve and reject. It calls function resolve() when the operation inside succeeds. On the contrary, reject() will be called when operation fails. The state of promise instance will be determined with calling these functions. There are following three states for promise instance.
・pending: initial state.
・fulfilled: meaning that the operation completed successfully
・rejected: meaning that the operation failed
When the promise instance is created, its state will be pending and it can either be fulfilled with a value or rejected with a reason(error) after the operation. When either of each options happens, the associated handlers will be called with chaining then/catch method to promise instance. You can write code as follows. In this code, promise means a promise instance.
When you use only then method, you can input two arguments. The first argument is the call back function which is fired when the state of promise instance become fulfilled, and it receives the result(value) of the asynchronous operation. On the contrary, the second argument is the function called when the state become rejected, and it receives error.
When we want to execute operation after multiple asynchronous operations end, how should we do? We have an option to use promise.all method. Promise.all method will receive the array which consists of promise instances, and return new promise instance. When all operations of promise instance end, its state will be fulfilled, and if each one of those operations fails, the state will be rejected. Following code is a rewrite of an example which loads an image, but it loads multiple images using promise.all method.(You can see live here: https://blackstone8960.github.io/article/async/promise-all.html)
Thus, the problem caused by Web workers will be solved using asynchronous operation and promise syntax. You will be able to write more functional code with using asynchronous programing. If you have a chance to try it, remember this site then :) Happy coding!
General asynchronous programming concepts
In this article, we'll run through a number of important concepts relating to asynchronous programming, and how this…
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting…
Web Design Leaves