This is the third day of my participation in the August More text Challenge. For details, see:August is more challenging

First of all, we all know that JS is single-threaded, so many methods do not need to be synchronized, but need to be asynchronous, how to execute? But how does a single thread perform on an asynchronous basis? The browser is multi-threaded and synchronizes execution with the kernel’s controls. A browser implements at least three resident threads: the JS engine thread, the GUI rendering thread, and the browser event triggering thread (UI thread).

SetTimeout implements asynchrony

For example, let code = 0; Function fun1() {// request interface to get code}function fun2() {// Request interface to exchange code for key} fun1(); fun2(); Fun1 (); fun2 (); fun1(); setTimeout(){=>{fun2(); 500}},Copy the code

Note: Using setTimeout may cause problems, the first method must not return, but because the setTimeout time is up, the fun2() is executed, and the code is not yet available, so it is not recommended.

2. Use the callback function

// Let code = 0; Function fun1(callback) {// request the interface to get code, call callback() in success; callback(); } function fun2() {// request interface to exchange code for key} fun1(fun2());Copy the code

Note: This will not cause setTimeout problems, but if many methods are related to each other, it may cause code continuity errors. If one method fails to execute, the entire page and JS code will fail to execute.

3. Promise objects

A Promise is an object. The difference between an object and a function is that an object can hold state and a function cannot (except for closures). It is mainly used for asynchronous operations, which can be queued.

Promises come in three states:

Pending waiting for

Fulfilled successfully

Rejected operation failed

A promise can only be fulfilled or rejected when it changes from a pending state, and it will never change again

let num = 10; let p1 = new Promise(function(reslove){ setTimeout(()=> { if(num > 10) { reslove(20); }else { reject(new Error('is a bug~')); } },1000) })function fun2() { num++; }p1.then(fun2()); //fun1 returns a promise, specifying a callback function fun2() that can execute multiple.then(); (Fun2 () had better be a Promise object, not detailed here)Copy the code

Promise.all() batch executes

let numFun = (num) => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(num) }, 1000) }) } let p1 = numFun(1) let p2 = numFun(2) Promise.all([p1 p2]).then((result) => { console.log(result); / / print} [1, 2]). The catch ((error) = > {the console. The log (error)})Copy the code

I am sorry that I did not write in detail because OF my poor health today. I will edit it after the challenge is over

4. Use async, await

The async keyword indicates that there are methods executed asynchronously throughout the code, but there may not be. There’s no limit to how many parameters you can pass; By default, the value resolve of the PROMISE object is returned.

Await can only be used in async defined methods, otherwise an error will be reported followed by a Promise object. If not, the system will automatically convert the await to a Promise object

Function fun1() {return "hello async"; } const result = fun1(); Then (STR => {console.log(STR); // Return a Promise object. // As with a Promise, the then method fun1().then(STR => {console.log(STR); })Copy the code

Used with await

async function fun1() { let res = await fun2(1); console.log(res); } function fun2(num){ num++; return num; }Copy the code

Five, event listening

The event types are click, ON, bind, Listen, addEventListener, and Observe

Event listening depends on when do you trigger, causing asynchrony

<div id="handlerClick1"> </div> function fun1() {setTimeout(()=> {fun2(); }) } $("#handlerClick1").click(function() { fun1(); }) function fun2() { console.log(23); }Copy the code

6. Publish Subscriber Mode (Observer Mode)

In simple terms, you order a subscriube on the ELM, the platform receives your request and starts to deliver, and the delivery guy completes the order (publish(‘done’)) and tells the platform that the order has been finished.

$subscribe('done',fun1); Publish ('done'); function fun1() {// publish('done'); // Tell elm to complete the order after delivery}Copy the code

A total of 6 kinds of sorting do not know all incomplete, write for two hours, feel to write quite little, when learning ~