A probe into JavaScript's single-threaded asynchronous mechanism

Source: Internet
Author: User
Tags event listener

Synchronous asynchronous mode for JavaScript

JavaScript's language execution environment is single-threaded. A single thread is one that wants to queue up so that tasks need to be done sequentially. The advantage of this model is that it is simple to implement, but the downside is that if there is a task in the queue that takes a long time, the task behind it must wait until the previous one executes, delaying the execution of the entire program.

To optimize this problem, the JavaScript language divides the execution pattern of the task into two types, synchronous (synchronous) and asynchronous (asynchronous).

The synchronous mode is that the latter task waits for the previous task to end and then executes, and the order of execution of the program is consistent and synchronized with the order of the tasks.

Asynchronous mode is completely different, each task has one or more callback functions, after the end of the previous task, not after the execution of a task, but the execution of the callback function, the latter task does not need to wait for the previous task to execute before execution, the execution order of the program is inconsistent with the order of execution of the task. On the browser side, a lengthy operation should be performed asynchronously to prevent the browser from losing its response.

There are several implementations of the async pattern,

There are four ways to implement asynchronous mode, callback function mode, Event listener mode, publish-subscribe mode and Promise Mode 1, callback function

The callback function is to pass the function as a parameter to the function that needs the callback to execute, for example F1 is time-consuming, F2 need F1 execution result to execute, F3 do not need f1,f2 result, need to execute as soon as possible,

So let's try to use Async to pass F2 as a parameter to the inside of the F1 callback function. Code as follows,

function F1 (func) {vartip ="'; SetTimeout (function () { for(vari =0; I <=10000; i++){                if(i = =10000) {Tip='F1 done, F2 need me.'} console.log (i);        } func (TIP); },0);    } function F2 (tip) {console.log (TIP); } function F3 () {Console.log ("f3 execution");    } f1 (F2); F3 ();

This asynchronous is implemented mainly by SetTimeout implementation, this function will be executed by the function to put the last side of the queue is the F3 behind, so F3 execution will be executed for the loop and F2,js is single-threaded, so the asynchronous implementation is actually time-consuming to put on the last side, After the tasks in the task process are executed, perform the tasks added later.

2, event monitoring

The idea is to use event-driven mode. The execution of a task does not depend on the order of the Code, but on whether an event occurs. This pattern is the same as the mechanism for binding events, such as binding a click event to a DOM element and executing a bound function when the click is triggered, so we are now simulating a done event, which is written in jquery. Binds a done event for F1, and executes F2 when the F1 occurs.

F1.on ('done', F2), function F1 () {setTimeout (function () {//  F1 task code  F1.trigger ('done'0);}

F1.trigger (' Done ') indicates that when execution is complete, the Do event is immediately triggered to begin execution of F2.

The difference between this and the callback function is that it depends on whether an event occurs to execute asynchronously, and the final implementation is settimeout implemented.

3, Subscribe/Publish

The difference between this and the event listener is the signal listener, assuming that there is a signal center, a task is done, like a signal center sends a signal, other tasks can subscribe to the signal center of the signal, so as to know when they can execute.

Event.subscribe ("done", F2), function F1 () {setTimeout (function () {// F1 's task code event.publish ("done");}

The F2 subscribes to the signal center for the done signal,

Event.publish ("Done"); This means that when the F1 executes, the signal center is released DONE,F2 receives the signal and starts to execute.

The 4,promise object is a specification proposed by the COMMONJS workgroup to provide a unified interface for asynchronous programming. Promise is defined within the ECMAScript 6 specification.

Promise is an object whose constructor receives a callback function that has two functions: execution in a successful state and failure state, promise three states, respectively: Waiting State (Pending), The execution State (fulfilled) and the rejection state (rejected).

var New Promise (function (resolve, reject) {  if (/**/) {    Resolve ( value);   Else {    reject (error);  }}); Promise.then (function (value) {  //  success}, function (value) {   // Failure });

The above code indicates that the promise constructor takes a function as an argument, and that the two parameters of the function are the Resolve method and the Reject method respectively. If the asynchronous operation succeeds, the state of the Promise object is changed to "succeeded" (that is, from pending to resolved) using the Resolve method, and if the asynchronous operation fails, the state is changed to "failed" (that is, from reject to pending) with the rejected method.

The then () method is the core of the Promise object, which returns a new Promise object, so it can be chained like jquery.

This is only a preliminary understanding of Promise, it belongs to ES6 new object, promise/deferred asynchronous model contains the programming idea is we should understand.

A probe into JavaScript's single-threaded asynchronous mechanism

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.