JavaScript's event model and promise implementation

Source: Internet
Author: User

1. JavaScript's run-time model-event loop
JS's runtime is a single-threaded runtime, unlike other programming languages such as c++,java,c#, which can be used for multithreaded operations. When it executes a function, it only goes to the black one way, and does not call other functions until the current function is finished (unless the current function calls other functions actively). It also doesn't have to worry about other threads interfering with it, because it runs with only one thread. If you remember some computer principles, this kind of runtime has only one stack, which is quite simple to design.

The design of a road to black is great, because it is simple enough, but who decides which function to execute from the beginning into the stack? The answer is that the JS runtime also has an event waiting queue with the stack, whenever the run stack is empty (that is, the current function runs the end), JS's runtime from the current event queue to take a message processing, to execute the message associated with the function. This behavior can be illustrated by the following code:

1  while (Eventqueue.waitformessage ()) {2let     event = eventqueue.pop (); 3     Let handler = Event.handler; 4     Handler ();                      // function to execute event Association 5     Context.scheduler.schedule ();   // let the scheduler handle other transactions 6 }

With the run stack and event queue, our JavaScript runtime is embryonic. However, the variables in JavaScript are objects, they are usually large size, not a small stack can be put down, if we are familiar with C + +, we will know that in C + + we only store the basic type (int, bool, etc.) and pointers in the stack, The pointer refers to the location of the memory heap is an address, which is the location of the JS object storage. The following figure can be used to visualize the JS runtime model.

2. Advantages and disadvantages of the event loop model
first of all, the pros. In addition to the simplicity of implementation, the greatest advantage of JavaScript is that it is completely asynchronous and never blocks . This sentence may be a bit confusing, how can a single-threaded runtime be completely asynchronous and never block? In fact, although the JS runtime single-threaded, but the browser is a multi-process multi-threaded environment , this point is the same in the backend, although node is a single-threaded JS runtime, but the back end there are other processes and threads with node to complete the response operation.

Open INDEXEDDB As an example, when you do indexedDB.open() , the current JavaScript run stack is finished, JS can handle other events related functions, so JS will not block. Who did the original open operation give to? The browser calls other threads to take over the process of opening the database, and when returned, the browser adds one 打开成功 or 打开失败 more events to the event queue at the JS Runtime and associates the callback function you added at that time with the event.

besides the shortcomings . We all know that JS call function only a path to the black, and there is no normal way to interrupt the process, if this is a long time (such as a large number of mathematical operations), will make JS into a class blocking state, the page will not respond. Wait a minute! Just said JS never block, here is how to come up with a class blocking it? At this time because of what we call blocking generally refers to IO blocking, that is, CPU, such as the end of the IO process, this situation in JS can never happen (note here is possible, not necessarily, some IO operation is a synchronous API can be called). The so-called class blocking state is the inevitable process of performing CPU-intensive tasks. So why does the page not respond in this situation? Because the browser will put the event into the event queue, but because the previous function has not finished, the page response event associated function is not executed, the natural page will show a state of unresponsive.

3. Implementation of Promise
Promise is a way of JS processing callback, is also the use of JS event loop model of a programming paradigm packaging, is also await async the basis of ES7. If the callback is the most straightforward and clumsy implementation of the JS event model, promise at least adds a dress to the callback to make it less ugly. But essentially, promise is a tool for describing the JS event loop model . Here is an example of how it links to the JS event model.

1Let Geturlasync = (url) = = {2Let promise =NewPromise (Resolve, reject) = {3Const XHR =NewXMLHttpRequest ();4Xhr.open (' GET ', URL);5Xhr.onload = () =Resolve (Xhr.responsetext);6Xhr.onerror = () =reject (xhr.statustext);7     });8     returnpromise;9 };TenGeturlasync (' http://exaple.com/text/11111 ') One. Then (res =Console.log (res)) A.Catch(Error = Console.log (error));

When callinggetUrlAsyncWhen the JS runtime does the following things:
1. You create aPromiseObject, or at this point in thegetUrlAsyncIn the stack frame;
2. Then create aXMLHttpRequestObject, or at this point in thegetUrlAsyncIn the stack frame;
3. CallXMLHttpRequestOfopenmethod, at this time the browser other threads take over the open process, JS without waiting for open end;
4. GivexhrOfonloadEvent to associate a handler function (delegate), noting that the event does not enter the event queue at this time;
5. GivexhrOfonerrorEvent is associated with a handler function (delegate), and the event does not enter the runtime's event queue at this time;
6. Incomingres => console.log(res)To materialize the Commission in the 4th step;
7. Incomingerror => console.log(error)To materialize the Commission in part 5th,at this point the current run stack exits and the runtime handles other events
At some point, the browser controls the open method to return, and itan event is added to the event queue in the JS runtimeLike whatonload
8. JS run-time loop toonloadEvent and find its associated handler, which in this case isres = console.log (res), and run the function.

Finally spit a trough a blog garden, still do not support markdown? The default editor is really very hard to use ....

JavaScript's event model and promise implementation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.