Asynchrony and synchronization

Synchronization: can get the result directly. For example, when you register at a hospital, you don’t leave until you get the number. Synchronization tasks can take anywhere from a few milliseconds to tens of milliseconds to get results.

Asynchronous: can’t get the result directly. For example, if you are waiting for a number at a restaurant, you can leave to do something else. You can check in every once in a while (polling), or you can get a message from your phone (callback).

Callback

A function written for other people is a callback. Assume the request. The onreadystatechange is intended for the browser calls, which means that the browser back to call this function. A callback is a function that is written but not called.

function f1(){}
function f2(fn){
  fn()
}
f2(f1)   
Copy the code

F1 is passed to F2, f2 calls F1, f2 does not call F1, so f1 is the function that F2 calls, so f1 is the callback.

The relationship between asynchrony and callback

  • Asynchronous tasks require callback functions to notify the result.
  • ForEach (n=>console.log(n)) is a synchronous callback.
  • Asynchrony often uses callbacks, but it doesn’t have to. Asynchrony involves not only callbacks but also polling.

Identify asynchrony and synchronization

Asynchronous:

SetTimeout AJAX (XMLHttpRequest) AddEventListenerCopy the code

Although AJAX can also be synchronized, do not set AJAX to synchronous because setting AJAC to synchronous will cause the page to freeze during the request.

Take an asynchronous example:

function yao(){
    setTimeout(() = >{
        return parseInt(Math.random() * 6) +1
    },1000)}Copy the code

Yao () does not return, and the arrow function returns the actual result. The arrow function is not executed immediately, so it is an asynchronous task/function.

Yao () returns an undefine value, so how do we get an asynchronous result? We can use a callback, write a function, and give it the address of that function,

function yao(fn){
    setTimeout(() = >{
        fn(parseInt(Math.random()*6) +1))},1000)
}
yao(console.log)  //function f1(x){console.log(x)}; The abbreviation of yao (f1)
Copy the code

Two asynchronous results

In AJAX, when we encounter the results of two asynchronous tasks, success and failure, we can do so in one of two ways

In method one, the callback takes two arguments, a success argument and a failure argument.

fs.readFile('/1.txt'.(error, data) = >{
  if(error){console.log('failure');return}
  console.log(data.toString()) / / success
})
Copy the code

Method 2: Write two callbacks

/ / parameters
ajax('get'.'1.json'.(data) = >{}, (error) = >{})

// Or object pass:
ajax('get'.'1.json', {success: () = >{},
  	fail: () = >{}}}Copy the code

But these two methods have drawbacks:

  • Non-standard, some people use success+error, some people use success+fail, some people use done+fail.
  • Prone to callback hell, code does not understand
  • Error handling is difficult

Promise

To solve these three problems, promises emerged.

The Promise object is used to represent the final completion (or failure) of an asynchronous operation and its resulting value.

Promise creation method

New Promise((resolve,reject) =>{resolve(result) reject(error) // reject(error)})Copy the code

Use of Promise

Ajax = (method, URL,options)=>{return new Promise((resolve,reject)=>{const {success,fail} = options, const sucess= options.success const fail = options.fail const request = new XMLHttpRequest() request.open(method,url) request.onreadystatechange = ()=>{ if(request.readyState ===4){ if(request.status<400){ resolve.call(null,request.response) }else { reject.call(null,request) } } } request.send() }) } ajax('get','/xxx').then( (Response)=>{}, // Success callback, only one argument (request)=>{} // failure callback, only one argument)Copy the code

Promise to summarize

  1. The return of new Promise ((resolve, reject) = > {… })
  2. Call resolve(result) if the task succeeds, call Reject (error) if the task fails.
  3. Resolve and reject call success and failure functions
  4. Pass in the success and failure functions using. Then (success, fail)