I. Asynchrony and synchronization

  • Sync: If you can get the result directly, it is synchronized

Eg: In the hospital registration, to get the number to leave the window, do not get the result will not leave

  • Asynchronous: Cannot get results directly

Eg: Wait at the door of the restaurant, get the number can go shopping, go to the restaurant every 10 minutes to ask (polling), or scan the code wechat to receive notification (callback)

Eg: AJAX, for example, the request. The send (), and not directly by the response, must wait until the readyState into 4, browser back call request. The onreadystatechange function, to get the request, the response

Second, the callback

Callbacks: A callback is not a callback but a function that you write for yourself

Eg: the request. The onreadystatechange is addressed to browser calls

  • function f1() {}
    function f2(fn){
        fn()
    }
    f2(f1)
    Copy the code
    • No call to f1
    • Pass F1 to F2
    • F2 calls F1
    • F1 is a callback

Asynchrony and callback

3.1 correlation

  • Asynchronous tasks need to tell JS to get the results when they get them
  • You can have JS write a function address (phone number) to the browser
  • The browser calls this function when the asynchronous task is complete.
  • And pass the result as an argument to the function.
  • This function is called by the browser, so it is a callback function

3.2 the difference between

  • Asynchronous tasks require callback functions to notify results, but polling can also be used

  • Callbacks do not have to be used only for asynchronous tasks, but can also be used for synchronous tasks

    Eg: array.foreach (n => console.log(n)) is a synchronization callback

Asynchronous functions

A function is asynchronous if its return value is in one of three apis (more on that later).

  • setTimeout
  • AJAX (i.e., the XMLHttpRequest)
  • AddEventListener

AJAX is generally not set to sync, which can cause the page to freeze during requests

4.1 Examples of Asynchronous Functions

  • functionRoll the dice,){
        setTimeout(() = >{// Arrow function
            return parseInt((Math.random()*6) +1
                            },1000)}Copy the code
    • Roll dice () does not write return, return undefined
    • There’s a return inside the arrow function that returns the actual result
    • This is an asynchronous function/task

How do I get asynchronous results?

  • You can write a function and give the address of the function to dice ().
 function f1(x){console.log(x)} Roll dice (f1)Copy the code
  • Then the dice roll function is required to get the result and pass the result as a parameter to F1
 function f1(x){console.log(x)} Roll dice (f1)functionRoll the dice,fn){
     setTimeout(() = >{// Arrow function
         fn(parseInt((Math.random()*6) +1)},1000)}Copy the code
  • Since f1 is only used once after the declaration, you can delete f1
 function f1(x){console.log(x)} Roll dice (f1)/ / toRoll the dice,x= > {
     console.log(x)
 })
  
 // If the number of arguments is not consistent, it cannot be simplified like thisRoll the dice,console.log)
Copy the code

Interview questions:

const array = ['1'.'2'.'3'].map(parseInt)
console.log(array)
// [1,NaN,NaN]

// The same as the following
const array = ['1'.'2'.'3'].map((item,i,arr) = >{ // Map passes three parameters to parseInt
    return parseInt(item,i,arr)
    //parseInt("1",0,arr) => 1
    //parseInt("2",1,arr) => NaN
    //parseInt("3",2,arr) => NaN parses 3 as a binary number
    
})
console.log(array)

// Normally it would be an arrow function
const array = ['1'.'2'.'3'].map(item= > parseInt(item))
console.log(array)
Copy the code

4.2 Processing different Results of asynchronous Tasks

4.2.1 Two processing methods

  • 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
  • Two callback
ajax('get'.'1.json'.data= >{},error= >{})
// The first function is a successful callback, and the second function is a failed callback
Copy the code

4.2.2 Deficiencies

  • Non-standard, various names, some people use success+error, some people use success+fail, and done+fail
  • Prone to callback hell, code is hard to understand
getUser( user= > {
    getGroups(user, (groups) = >{
        groups.forEach( (g) = >{
           g.filter(x= > x.ownerId === user.id)
              .forEach(x= > console.log(x))
                })
        })
})
// This is just a four-level callback
Copy the code
  • Error handling is difficult

4.3 Promise

Take AJAX encapsulation as an example

ajax = (method, url, options) = >{
    const {success, fail} = options // Destruct assignment
    const request = new XMLHttpRequest()
    request.open(method, url)
    request.onreadystatechange = () = >{
        if(request.readyState === 4) {// Call success. Call 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) = >{}  // The left side is short for function and the right side is arrow function
})

Copy the code

I’m going to write it as a Promise, so I’m going to call the function

ajax('get'.'/xxx')
    .then((response){},(request) = >{})
// The first argument to then is success and the second argument is fail
// Ajax () returns an object containing the.then() method

Copy the code

Next, modify the ajax source code

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

Disadvantages of encapsulated AJAX

  • Post failed to upload data. Procedure
  • The request header cannot be set

How to solve:

  • Using jQuery. Ajax
  • Using axios