asynchronous

Asynchrony is divided into three types of code in JS

  1. Ajax
  2. addEventListener
  3. setTimerout()

Asynchronous code is executed at some point in the future, during which time the browser can execute other code.

Asynchrony is necessary. Imagine an Ajax request being executed synchronously, where the browser stops the execution of other programs because it is waiting for a request. Clicking on the browser in this case doesn’t give you any feedback.

So never use the second parameter in the XMLHttpRequest class (which sets whether the Ajax request is asynchronous).

Ajax

Asynchronous JavaScript + XML is not a new technology per se, but a new term coined in 2005 by Jesse James Garrett. The main function is to make a request to the server without refreshing the browser.

Four steps

The XMLHttpRequestAPI is at the heart of Ajax. There are only four steps to complete a request using Ajax:

1. The XMLHttpRequest class creates a request. 2. Call open to open a request. 3. Listen for the onReadyStatechange event, which listens for the lifecycle from a request to a response. 4. Invoke the send method to send the request

So if we simplify this

  1. Create a request
  2. Open the request
  3. Listening to the response
  4. Send the request

The code is shown as follows:

const request = XMLHttpRequest();
request.open("GET","baidu.com");
request.onreadystatechange = ()=>{
	if(request.readyState === 4){
    	if(request.status >= 200 && request.status <400){
        	//success
        }else{
        	//error
        }
    } 
}

request.send();
Copy the code

XMLHttpRequest. ReadyState lifecycle status code

Request. status Indicates the status code of the response

The callback function

How to understand a callback?

The callback function follows two principles:

  1. Written methods are not called by themselves, but by others (by which I mean other functions).
  2. Methods will be executed by someone else at some point in the future, rather than being manually invoked by the developer himself.

Methods that are not called directly by themselves count as future execution, such as fn(), which means I am now executing fn() immediately.

The function is a callback if it complies with the above two rules.

Callback function: I’ll call it later, not now.

Callbacks are often used to handle asynchrony

Take a chestnut

Callback functions in asynchronous code

fn(){
	console.log('hi');
}
setTimeout(fn,1000);
Copy the code

In this code I declare a fn function, and you can see that I just declared it and didn’t call it. Instead, setTimeout calls the fn function after 1000 milliseconds. So it fits the two rules above

Foreach loop in native JS and each loop in jQuery

Let array =,33,4,12,5,1 [12]; Function foreach(fn){for(let I =0; i<this.length; i++){ fn(this[i],i,this); }} // Call foreach.call(array,console.log)Copy the code

So you can see that the FN in foreach, I’m not calling it but foreach is calling it, I’m just declaring an anonymous function and passing it in. This function is the log method on the console object. The function is executed in the future (the future in this case is executed in foreach’s own procedure).

If the foreach method on the Array prototype is used, the foreach method on the Array prototype is completely usable.

It also illustrates why a return in foreach cannot directly prevent the foreach function from executing.

The return does interrupt a function but the fn callback in foreach. After the foreach function returns, the foreach for loop will execute as usual. So a return can only achieve a continue.

Promise

Promise regulates how asynchronous code should be handled, and like Ajax, promises are not a new technology.

Js before Promise, using callback functions was the preferred way to handle asynchronous code, and there was no universal way to handle callbacks.

For example, ajax encapsulation can have many types of writing. Some people use success and error to denote success and error. Some people use success and fail to refer to successful and failed callback functions. Some people take arguments to objects (which contain callback functions), while others take arguments directly to callback functions. There is no uniform norm at all.

Use Promise to encapsulate Ajax

function ajax(method,url,data){ return new Promise((resolve,reject)=>{ const request = XMLHttpRequest(); request.open(method,url); request.onreadystatechange = ()=>{ if(request.readyState === 4){ if(request.status >= 200 && request.status <400){ resolve(request.response); }else{ reject() } } request.send(data); }})Copy the code

This will unify the way Promise handles asynchronous code

ajax("GET",baidu.com)
.then((data)=>{})
.catch((err)=>{})
Copy the code

Promise.all

The promise.all (iterable) method returns an instance of a Promise that will be resolved if all promises in iterable arguments are completed (resolved) or if no promises are included in the arguments; If the promise parameter has a failed (Rejected), this instance calls back failed (Reject), which is the result of the first failed promise.

const promise1 = Promise.resolve(3); const promise2 = 42; const promise3 = new Promise((resolve, reject) => { setTimeout(resolve, 100, 'foo'); }); Promise.all([promise1, promise2, promise3]).then((values) => { console.log(values); / / / 3 lancet, 'foo'});Copy the code

Promise.race

The promise.race (iterable) method returns a Promise that is resolved or rejected once a Promise in the iterator is resolved or rejected.

This is equivalent to all of the promises in the array being executed at the same time, and the fastest promise is returned

const promise1 = new Promise((resolve, reject) => {
  setTimeout(resolve, 500, 'one');
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'two');
});

Promise.race([promise1, promise2]).then((value) => {
  console.log(value); // 'two'
});

Copy the code