Asynchrony and callback

1. What is asynchronous? If the results can be retrieved directly are synchronous and the results cannot be retrieved directly are asynchronous (retrieved indirectly through polling or callback)

2. What is a correction? Write a function for your own use, not a callback; But to others use function, it is the callback, namely just having no matter have, for example With AJAX, for example, the request. The onreadystatechange is addressed to browser calls, for example

Function f1(){} function f2(fn){fn()} f2(f1) //f1 is a callback, because f1 is not called, but f1 is called by another function (f2)Copy the code

3. The relationship between asynchrony and callback? (Partnership, not necessarily reciprocal)

Related:

  • Asynchronous tasks need to notify JS to take the results when they get themCopy the code
  • How? When the asynchronous task is completed, the browser calls the address of the function. At the same time, the result is passed as a parameter to the function. This function is called for the browser, so it is a callback functionCopy the code

The difference between:

  • Asynchronous tasks require callback functions to notify the resultCopy the code
  • But the callback function doesn't have to be used only in asynchronous tasksCopy the code
  • Callbacks can also be used in synchronization tasksCopy the code
  • Array.foreach (n=>console.log(n)) is a synchronization callbackCopy the code

Function f1(x){console.log(x)} function f(fn){setTimeout(()=>{fn(parseInt(math.random ()*6)+1); },1000)} f(f1)


function f1(x){console.log(x)} f(f1)


To: f (x = > {the console. The log})

The use of Promise

Callback method for two results; 1. Method 1: The callback takes two arguments

Fs. ReadFile ('. The / 1. TXT ', (error, data) = > {the if (error) {the console. The log (' failure '); Return} console.log(data.tostring ())// success})Copy the code

2. Method 2: Make two callbacks

ajax('get',url,data=>{},error=>{})
ajax('get',url,{
    success:()=>{},fail:()=>{}
})

Copy the code

Reasons for using Promises (or rather, drawbacks of other approaches:) :

One is not standard, there is no written provisions

The second is callback hell, where the code becomes hard to understand

Third, error handling is difficult

For these reasons, promises come into being

ajax = (method,url,options)=>{ const {sucess,fail} = options const request = new XMLHttpRequest() request.open(method,url) request.onreadystatechange = ()=>{ if(request.readyState === 4){ if(request.status < 400){ sucess.call(null,request.response) }else if(request.status >= 400){ fail.call(null,request,request.status) } } } Request.send ()} {request. Send ()}} Ajax ('get','/ XXX ',{success(response){},fail (request,status)=>{}})//Copy the code

Change this code to Promise

ajax = (method,url,options)=>{ return new Promise((resolve,reject)=>{ const {success,fail} = options const request = new  XMLHttpRequest() request.open(method,url) request.onreadystatechange = ()=>{ if(request.readyState === 4){ // Successfully call resolve, Reject if(request.status < 400){resolve. Call (null,request.response)}else if(request.status >= 400){reject if(request.status >= 400){ reject.call(null,request) } } } request.send() }) }Copy the code

Return new Promise((resolve,reject)=>{})

Iii. Handwritten Promise:

A Promise has three states: Pending, a pity success, and Rejected failure.

Write a Promise code like this:

function Promise(executor){ let self = this; self.status = 'pending'; // wait state self.value = undefined; Self. value = undefined; Resolve (value){if(self.status === 'pending'){self.status = 'resolved'; self.value = value; } } function reject(reason){ if(self.status === 'pending'){ self.status = 'rejected'; self.reason = reason; } } try{ executor(resolve,reject); }catcch(e){ reject(e); // An exception occurred during the capture. Prototype. Then = function(onFufiled,onRejected){let self = this; if(self.status === 'resolved'){ onFufiled(self.value); } if(self.status === 'rejected'){ onRejected(self.reason); } } module.exports = Promise;Copy the code

Iv. Interview questions about Promise:

Promise methods: Then, all, race, catch, finally

The then() method: returns a Promise with up to two arguments: a callback for the success and failure of the Promise. All () : race() :Copy the code