I. Synchronous and asynchronous

1.1 Understanding Synchronous and Asynchronous

Definition: Synchronous and asynchronous are concerned with *Message communication mechanism *Synchronous communication/ Asynchronous communication. == synchronization, when something is called, the caller has to wait for the result of the call to return before it can proceed. == == asynchronous, as opposed to synchronous, the caller does not understand the result. Instead, after the call is made, the caller can continue to perform subsequent operations. The caller can notify the caller through the file or handle the call by calling back the function ==

** For example: ** you go to the mall to buy something, you like a mobile phone, you can tell the shopkeeper that you have this phone, he will go to the warehouse to pick up the goods, you have to wait in the store, can not leave, this is called synchronization. Now you buy mobile phone to follow the fashion directly to jingdong place an order, place an order after you can do other time (chasing drama, playing king, LOL) and so on goods to sign for it. This is called asynchrony.

1.2 To be more specific, take our method call:

  • Once a synchronous method call has started, the caller must wait until the method call returns before continuing with the subsequent behavior.
  • Asynchronous method invocation is more like messaging; once initiated, the method invocation is returned immediately and the caller can continue with subsequent operations. Asynchronous methods, on the other hand, usually execute “realistically” in another thread. The whole process does not hinder the caller’s work

1.3 I add two pictures to make you understand ** better

1.3.1Synchronous execution

[]

Synchronous execution When the calling method completes execution and returns the result, subsequent code can be executed

1.3.2 Asynchronous Execution

[]

For asynchronous calls, you can refer to Ajax, and instead of waiting for the sum method to complete, you can execute the subsequent code directly. The sum method notifies the main thread of its status after execution, or handles the results of the asynchronous method through callbacks

1.4 Synchronous asynchrony is not the same as blocking and non-blocking

Looking at the above explanation, you might say isn’t that the blocking mechanism? No, no, no, synchronous asynchrony is not to be confused with blocking non-blocking.

Blocking and non-blocking emphasize the state of the program as it waits for the result of the call (message, return value). A blocking call means that the current thread is suspended until the result of the call is returned. The calling thread does not return until it gets the result. A non-blocking call does not block the current thread until the result is not immediately available. For synchronous calls, most of the time the current thread is still active, but logically the current function does not return, that is, the synchronous wait does nothing, wasting resources.

Synchronous and asynchronous emphasize the message communication mechanism. Synchronization is when a “call” is made, and the “call” does not return until the result is received. But once the call returns, you get the return value. In other words, the “caller” actively waits for the result of the “call”. Asynchronous, on the other hand, when the call is made, the call returns directly, so no result is returned. In other words, when an asynchronous procedure call is made, the caller does not get the result immediately. Instead, after the “call” is issued, the “called” notifies the caller through a status, notification, or callback function

2. Introduction of Promise

Promise is a solution to asynchronous programming that makes more sense and is more powerful than traditional solutions — callback functions and events. It was first proposed and implemented by the community, and ES6 has written it into the language standard, unifying usage, and providing Promise objects natively.

== function: Avoids callback hell by changing asynchronous code to call like synchronous code. = =

A Promise is simply a container that holds the result of an event (usually an asynchronous operation) that will end in the future. Syntactically, a Promise is an object from which to get messages for asynchronous operations. Promise provides a uniform API, and all kinds of asynchronous operations can be handled in the same way

2.1 A Promise object has three states:

  • Pending: An initial state that is neither successful nor failed.
  • This is a big pity: it means that the operation will be completed successfully.
  • Rejected: Indicates that the operation fails.

2.2 PromiseObjects have the following two characteristics:

(1) The state of the object is not affected by the outside world. The Promise object represents an asynchronous operation with three states: Pending, fulfilled and Rejected. == Only the result of the asynchronous operation can determine the current state, and no other operation can change the state. That’s where the name comes from. The English word “Promise” means nothing that can be changed.

(2) Once the state changes, it will never change again, and this result can be obtained at any time. There are only two possibilities for the state of the Promise object to change from pending to depressing and from pending to Rejected. As long as these two things are happening the state is fixed and will not change – it will remain the same and this is called resolved. If the change has already occurred, you can add a callback to the Promise object and get the same result immediately. This is quite different from an Event, which has the characteristic that if you miss it and listen again, you will not get the result.

Summary:

  1. Promise is a constructor, and the new instance object can help us solve some of the problems of asynchronous manipulation
  2. When we encounter asynchronous operations, we can use promises to process them for later code writing

Three.Promise produces a background

If you’re making Ajax requests that require multiple requests to be completed in a certain order, it’s easy to create == callback hell if you don’t use a Promise implementation

Such as:

  /* 
    Ajax回调地狱
     */
    / / don't have to write


    // http://kumanxuan1.f3322.net:8809/index/banners/travel
    // http://kumanxuan1.f3322.net:8809/strategies/themes
    // http://kumanxuan1.f3322.net:8809/travels/query

    // After the first page is rendered. Do the second page render
    // After the second page is rendered. Do a third page render
    $.ajax({
      url: "http://kumanxuan1.f3322.net:8809/index/banners/travel".type: "GET".success(res) {
        if (res.code == 200) {
          console.log("First request completed");
          console.log("I'm 100 lines of code.");
          // The request must be sent after the first completion
          $.ajax({
            url: "http://kumanxuan1.f3322.net:8809/strategies/themes".type: "GET".success(res) {
              if (res.code == 200) {
                console.log("Second request completed");
                console.log("I'm 100 lines of code.");
                $.ajax({
                  url: "http://kumanxuan1.f3322.net:8809/travels/query".type: "GET".success(res) {
                    if (res.code == 200) {
                      console.log("Third request completed.");
                      console.log("I'm 100 lines of code."); }}})}}})Copy the code

This code is disgusting and very difficult to maintain in the future, so we don’t recommend it.

Summary: Promise was invented to solve the problem of multi-layer nesting of asynchronous callbacks (hell callbacks)

Basic use of Promise

Promise execution process

Make a Promise

// Default pending: initial state
var p=new Promise(function (resolve,reject) {
    if("Operation successful"){
        resolve();//pending--> depressing the callback function that succeeds the asynchronous operation
    }else{
        reject(); //pending-->reject Callback function for asynchronous operation failure
    }
})
p.then(data= > {// Call the logic outside then to handle success
    console.log("Handling the logic of success.");//fulfilled  
}).catch(err= >{// Call the logic outside the catch to handle the failure
    console.log("Failed logic.");//reject
})
// Then methods are called after asynchrony succeeds, and catch methods are called after asynchrony fails
Copy the code

Such as:

let flag = false;
let p = new Promise((resolve, reject) = > {
    if (flag) {
        resolve("Do a great thing.");
    } else {
        reject("Say I'm sorry."); }}); p.then((data) = > {
    console.log("I want" + data); //fulfilled
}).catch((err) = > {
    console.log("I want" + err); //reject
});
Copy the code

Use Promise to solve callback hell

Features of the then chain call of Promise: If the first then parameter receives a promise, the next then parameter receives a promise. If the first then parameter receives a promise, the next THEN parameter receives a promise. It’s the actual argument inside the Promise object when resolve is called

5.1 how to resolve multiple requests (Callback Hell)

let p1 = new Promise((resolve,reject) = >{
  $.ajax({
    url:'url1'.success(res){
      resolve(res)
    },
    error(err){
      reject(err)
    }
  })
})
let p2 = new Promise((resolve,reject) = >{
  $.ajax({
    url:'url2'.success(res){
      resolve(res)
    },
    error(err){
      reject(err)
    }
  })
})
let p3 = new Promise((resolve,reject) = >{
  $.ajax({
    url:'url3'.success(res){
      resolve(res)
    },
    error(err){
      reject(err)
    }
  })
})

p1.then(res1= >{
  console.log('First request completed')
  return p2;
}).then(res2= >{
  console.log('Second request completed')
  return p3
}).then(res3= >{
  console.log('Third request completed')})Copy the code

So we used Promise to solve the problem of nested callback functions inside callback functions.

Summary: We can use multiple promises to call the THEN method to turn the hell callback into chained programming for later maintenance

5.2. Simplify the promise writing for multiple requests

 <script src=". / jquery - 1.11.3. Js. ""></script>
  <script>
    // Multiple requirements function encapsulation
    function proAjax(url) {
      return new Promise((resolve, reject) = > {
        $.ajax({
          url,
          type: "GET".success(res) {
            resolve(res);
          },
          error(err){ reject(err); }})})}let p1 = proAjax("http://kumanxuan1.f3322.net:8809/index/banners/travel");
    let p2 = proAjax("http://kumanxuan1.f3322.net:8809/strategies/themes");
    let p3 = proAjax("http://kumanxuan1.f3322.net:8809/travels/query");


    p1.then(res= > { / / asynchronous
      // Handle the correct business logic
      console.log("The first");
      return p2; // Change the direction of.then
    }).then(res= > {
      console.log("The second");
      return p3;
    }).then(res= > {
      console.log("The third");
    })


    // 1. Fixed the problem of callback hell
    // 2. Asynchronous code looks like synchronous code
    // 3. Definition: Promise asynchronous programming solution
Copy the code

Vi.Promise encapsulates AJAX (Extension)

In the future, you’ll learn a library — Axios — based on Promise, which is essentially a wrapper around native AJAX.

So, let’s also try wrapping an AJAX function with Promise:

function ajax(options) {
    // This options is a configuration parameter passed to Ajax
    return new Promise((resolve, reject) = > {
        let method = options.method || "GET"; // If there is no request mode, the default is get
        let data = options.data || ""; // Request parameters are null by default
        let xhr = new XMLHttpRequest();
        if (method === "GET") {
            xhr.open(method, options.url+"?"+data);//get uses the URL to pass parameters
            xhr.send();
        } else if (method === "POST") {
            xhr.open(options.method, options.url);
            // The request header needs to be set for post
            xhr.setRequestHeader("Content-Type"."application/x-www-form-urlencoded");
            xhr.send(data);
        }
		// Listen to the function
        xhr.onreadystatechange = () = > {
            if (xhr.readyState == 4 && xhr.status == 200) {
                // The response succeededresolve(xhr.responseText); }}; xhr.onerror =(err) = > {
            reject(err);
        };
    })
}


ajax({
    method:"GET".url:"http://kumanxuan1.f3322.net:8809/travels/query".data:"orderType=1&currentPage=1"
}).then(res= >{
    console.log(res);
}).catch(err= >{
    console.log(err);
})

ajax({
    method:"POST".url:"http://kumanxuan1.f3322.net:8809/users/login".data:"username=123&password=123"
}).then(res= >{
    console.log(res);
}).catch(err= >{
    console.log(err);
})
Copy the code