The asynchronous and single-threaded javascript

Source: Internet
Author: User

First, preface

As we all know, Javasript is a single-threaded language, the so-called single-threaded is not the same time to do two things, two pieces of code can not be executed simultaneously, because this mechanism to avoid the two-segment JS at the same time a DOM node rendering conflict. But there will be a problem, for example, there is a very time-consuming operation in JS execution, because JS is executed sequentially, so it will lead to the code stuck in this time-consuming method there, resulting in the state of the page suspended animation, in order to solve this problem, JS also provides some solutions, such as Ajax, SetTimeout, SetInterval, provides a solution that is asynchronous. Some people would say that the single-threaded and asynchronous simultaneous existence of a language is not a conflict? In fact, JS is a single-threaded language, but the browser is not a single-threaded ah, the browser for the execution of JS assigned a main thread, you can also open up a sub-thread in some way to perform the time-consuming Operation JS, and then return to the main thread in the form of callback to execute, So asynchronous is just a single-threaded solution, and cannot change the nature of the JS language as a single-threaded language.

Second, asynchronous

1. Implementing asynchronous (EventLoop) event polling

EventLoop, which is the event polling, is the specific way that JS implements Async, when JS executes sequentially, it encounters an asynchronous function, it puts the asynchronous function in the asynchronous queue, and polls the function in the asynchronous queue after the synchronization function finishes executing.

The event polling will always query for asynchronous functions in the async queue, so after the first point of the function execution completes, wait a second after the asynchronous queue is found Func2 This function appears in the asynchronous queue, so the event polling query to this function, and put this function into the main process execution. Where both func1 and Func2 are part of the asynchronous function's back-off function.

2, asynchronous several solutions

(1) deffered in jquery

1 function Test () {2     varDT = $. Deferred ()3     varwait =function (dt) {4         varTask =function () {5Console.log ('deffered is ok!')6Dt.resolve ()//Success7             //Dt.reject ()//failed8         }9SetTimeout (Task, +)Ten         returndt.promise () One     } A     returnWait (DT) - } -  the varW =Test () - //W.reject ()//executing reject () here will cause the next function to go to error, so you need to change the returned object to return promise - $.when (W). Then (function () { -Console.log ('Ok1') + }, Function () { -Console.log ('Error1') + }) A W.then (function () { atConsole.log ('Ok2') - }, Function () { -Console.log ('Error2') -})

The Deffered object can be actively modified resove or reject,promise can only be passively monitored

(2) Promise

Promise in ES6 is really listed as the standard, about promise here only a few use scenes,

Concatenation: The second asynchronous execution may depend on the result of the first asynchronous execution

1 function loadimg (src) {2   varPromise =NewPromise (Resolve, reject) = {3     varimg = document.createelement ('img')4     //throw new Error (' This is a error! ') //throws an exception5Img.onload =function () {6 Resolve (IMG)7     }8Img.onerror =function () {9Reject'Picture onload error!')//passing in a message will go to catch to catch an errorTen     } OneIMG.SRC =src A   }) -   returnPromise - }; the //Promise Series Loading - varsrc =' **********************' - varresult =loadimg (SRC) - varSRC1 =' **********************' + varRESULT1 =loadimg (SRC1) -  +Result.then (() = { AConsole.log (' First') at   returnResult1//The Result1promise instance is returned here, and the result is returned by default if not returned -}). Then (() = { -Console.log ('Second') -}).Catch(Error) = { - Console.log (Error) -})

Promise.all pass in an array, which is the callback function that will not go until all of the functions have been executed.

1 promise.all ([result, RESULT1]). Then (function(res) {2     /// logic 3 } after completion of all executions )

Promise.race also passes in an array where the callback function is taken whenever an asynchronous function is completed

1 promise.race ([result, RESULT1]). Then (function(res) {2     ///  Logic 3} After completion of all executions  )

(3) async/await

This method is not in the ES6 standard, ES7 introduced, has not become a standard, compared to promise it is only in the way of executing callbacks, followed by a promise, Just behind the promise. Then the asynchronous callback method is still used, and async is using the synchronous method

1 function () {2     const result = await loadimg (SRC)3    console.log (result.width)  4     Const RESULT1 = await loadimg (SRC1)5    Console.log ( Result1.width)6 }

The above is the content of this discussion, the shortcomings also please correct me

The asynchronous and single-threaded javascript

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.