asynchronous

What is asynchrony? What is synchronization?

Sync – Get the results directly

Asynchronous – Can’t get results directly

Asynchronous, for example,

With AJAX, for example

Request. The send (), and not directly by the response, must wait until after the readyState into 4, browser back call request. The onreadystatechange function, to get the request, the response.

The callback callback

Write a function for your own use, not a callback

A function written for other people is called a callback

Request. The onreadystatechange is addressed to browser calls, meaning the browser back to call this function.

The callback example
  • I’m going to give function 1 to another function 2

    function f1(){}
    function f2(fn){
    	fn()
    }
    f2(f1)
    Copy the code
  • Analysis of the

    It doesn’t call f1, but it passes f1 to F2, f2 calls f1, f1 is the function that F2 calls, and f1 is the callback.

  • Carrying it

    Function f1(x){console.log(x)} function f2(fn){fn(' hello ')} f2(f1)Copy the code

    How can F1 have an x parameter?

    Fn in fn(‘ hello ‘) is f1, and ‘hello’ is assigned to parameter x

Asynchrony and callback

associated

The asynchronous task needs to notify JS to get the result when it gets the result. You can ask JS to leave a function address to the browser. When the asynchronous task is complete, the browser can call the function address and pass the result as a parameter to the function.

The difference between

Asynchronous tasks need to use callback functions to notify results, but callback functions are not necessarily exclusive to asynchronous tasks

Callbacks can also be used in synchronization tasks

Array.foreach (n=>console.log(n)) is a synchronization callback

Judge synchronous asynchrony

Judgment method

A function is asynchronous if its return value is in one of the following three cases

SetTimeout AJAX //(XMLHttpRequest) AddEventListenerCopy the code

Yes, AJAX can be set to sync, but it’s not necessary, as doing so would cause the page to freeze during the request.

For example
Roll the dice
functionRoll the dice,){
	setTimeout(() = >{
	 return parseInt(Math.random()*6) + 1 / / 1-6 at will},1000)
	//return undefined
}
Copy the code
Analysis of the

Roll dice () without return, return undefined

The arrow function has a return, which returns the actual result

So this is an asynchronous function/task

Dice roll optimization – callback
function f1(x){console.log(x)} // Use the callback to pass the result of the dice roll function as an argument to f1
functionRoll the dice,fn){
	setTimeout(() = > {
		fn(parseInt(Math.random()*6) + 1)},1000)}Copy the code
Roll dice – Simplifies arrow functions

Since f1 is only used once after the declaration, you can delete f1

function f1(x){console.log(x)} Roll dice (f1)Copy the code

Instead of

Roll the dice,x= >{console.log(x)})
Copy the code

To simplify the

Roll the dice,console.log) // If the number of parameters is inconsistent, it cannot be simplified in this way, as in the following interview question
Copy the code

The interview questions

Restore the complete code

ParseInt (String,radix) parses a string and returns a decimal integer of the specified radix

const array = ['1'.'2'.'3'].map((item,i,arr) = >{
	return parseInt(item,i,arr)
	ParseInt ('1',0,arr) => 1
    // parseInt('2',1,arr) => NaN
    // parseInt('3',2,arr) => NaN
})
Copy the code

That’s how you get the answer you want

I could write it as shorthand

The use of the Promise

What if an asynchronous task has two outcomes — success or failure?

Method 1 — The callback takes two arguments
fs.readFile('./1.txt'.(error,data) = >{
	if(error){console.log('failure');return}
	console.log(data.toString()) / / success
})
Copy the code
Method 2 — Use two callbacks
ajax('get'.'/1.json'.data= >{},error= >{})
// One successful callback, one failed callback


ajax('get'.'/1.json', {success: () = >{}, fail: () = >{}})// Accept an object with two keys representing success and failure
Copy the code

The above methods have some disadvantages:

  1. Non-standard, multifarious names, no written provisions. Some people use success+error, some people use success+fail, some people use done+fail.

  2. Prone to callback hell, code becomes unreadable

    For example,

    getUser(user= > {
    	getGroups(user.(groups)=>{
    		groups.forEach((g) = >{
    			g.filter(x= > x.ownerId === user.id)
    			.forEach(x= > console.log(x))
    		})
    	})
    })
    Copy the code
  3. Error handling is difficult

How to solve the callback problem?

  1. Specify the name or order of the callbacks
  2. Reject callback regions to make code more readable
  3. Easy to catch errors

Promise

In 1976, Daniel P.Friedman and David Wise proposed the idea of Promise

Later generations invented Future, Delay, Deferred and so on based on this

The front end combines Promise and JS to develop the Promise/A+ specification

The specification details how Promise works and how to use it

Take AJAX encapsulation as an example
ajax = (method,url,optiopns) = > {
	const {success,fail} = options // Destruct assignment
	const request = new XMLHttpRequest()
	request.open(method,url)
	request.onreadystatechange = () = > {
		if(request.readyState === 4) {// Call success and fail
			if(request.status < 400){
				success.call(null,request.response)
			}else if(request.status >= 400){
				fail.call(null,request,request.status)
			}
		}
	}
	request.send()
}

ajax('get'.'/xxx', {success(response){}, fail:(request,status) = >{}})// Success = function
Copy the code
I’ll write it as Promise
ajax = (method,url,options) = > {
	return new Promise((resolve,reject) = >{
		const {sucess,fail} = options
		cosnt request = new XMLHttpRequest()
		request.open(method,url)
		request.onreadystatechange = () = >{
			if(request.readyState === 4) {// Call resolve on success, reject on failure
				if(request.status < 400){
					resolve.call(null,request.response)
				}else if(request.status >= 400){
					reject.call(null,request)
				}
			}
		}
		request.send()
	})
}

ajax('get'.'/xxx')
	.then((response) = >{}, (request,status) = >{})
// Rewrite is a callback, but success and fail are not required
// Then the first argument is success, then the second argument is fail
// Ajax () returns an object containing the.then() method
Copy the code

Two-step –

  1. return new Promise((resolve,reject)=>{... })

    Call resolve(result) if the task succeeds

    Call result(error) if the task fails

    Resolve and reject call success and failure functions

  2. Pass in the success and failure functions using. Then (success,fail)

The above encapsulates ajax’s shortcomings

  • Post failed to upload data. Procedure

    Request. Send (where you can upload data)

  • The request header cannot be set

    request.setRequestHeader(key,value)

  • How do you solve it?

    Continue to refine Ajax

    Using jQuery. Ajax

    Using axios

jQuery.ajax

Chinese document

Advantages:

Support for more forms of parameters

Supporting Promise

Support more functions

axios

The latest AJAX library

Code sample

axios.get('5.json')
	.then(response= >
	console.log(response)	
)
Copy the code

Advanced usage —

  • JSON automatic processing

    Parse automatically calls json.parse when Axios finds that the content-type of the response is JSON, so setting the content-type correctly is a good habit

  • Request interceptor

    You can add something to all requests, such as query parameters

  • Response interceptor

    You can add something to all the responses, or even change the content

  • Can generate different instances (objects)

    Different instances can set different configurations for complex scenarios