The most user-friendly explanation of Promise

Promise

  • promise The syntax is a ES6
  • Commitment means, is designed to solve the asynchronous callback hell problem

Callback

  • What is a callback function?

  • A function is to function as a parameter passed to the B

  • B in the function call to the way reference line

    function a(cb) {
      cb()
    }
    
    function b() {
      console.log('我是函数 b')
    }
    
    a(b)
    
  • Why do we need a callback function

    • When we perform an asynchronous behavior, we need to do something after a asynchronous behavior is finished
    • So, we have no way to predict in advance what time this asynchronous behavior is done
    • We can only be in the form of a callback function to perform
    • For example, we will package that ajaxfunction insidesuccess
    • We do not know when ajax request is complete, it is necessary to form callback function to

Callback Hell

  • When a nested callback function when a callback function

  • There will be a nested structure

  • When the situation will be more nested callback hell

  • For example, we send three ajax request

    • The first normal transmission
    • A second result value of a first request requires a request as a parameter
    • A third result value of a request requires a second request as a parameter
    ajax({
      url: '我是第一个请求',
      success (res) {
        // 现在发送第二个请求
        ajax({
          url: '我是第二个请求',
          data: { a: res.a, b: res.b },
          success (res2) {
            // 进行第三个请求
            ajax({
              url: '我是第三个请求',
              data: { a: res2.a, b: res2.b },
      				success (res3) { 
                console.log(res3) 
              }
            })
          }
        })
      }
    })
    
  • Callback hell, in fact, due to too many nested callback function

[Image dump the chain fails, the source station may have security chain mechanism, it is recommended to save the picture down uploaded directly (img-ZKGK3zM5-1583940456426) (./ assets / callback hell .jpeg)]

  • When this structure later became the code, will not be possible to maintain the
  • So we need to write code for some of the more artistic

PROMISE

  • In order to solve the callback hell

  • We will use the promise grammar

  • grammar:

    new Promise(function (resolve, reject) {
      // resolve 表示成功的回调
      // reject 表示失败的回调
    }).then(function (res) {
      // 成功的函数
    }).catch(function (err) {
      // 失败的函数
    })
    
  • promise is a grammar

    • Each of our asynchronous event, at the time of execution
    • There will be three states, implementation / success / failure
  • Because it contains a successful callback function

  • So we can use the promise to solve the problem of sending multiple ajax

    new Promise(function (resolve, reject) {
      ajax({
        url: '第一个请求',
        success (res) {
          resolve(res)
        }
      })
    }).then(function (res) {
      // 准备发送第二个请求
      return new Promise(function (resolve, reject) {
        ajax({
          url: '第二个请求',
          data: { a: res.a, b: res.b },
          success (res) {
            resolve(res)
          }
        })
      })
    }).then(function (res) {
      ajax({
        url: '第三个请求',
        data: { a: res.a, b: res.b },
        success (res) {
          console.log(res)
        }
      })
    })
    
  • This time, our code has changed a lot

  • Basically been maintained

  • But for a programmer, like this it is not enough

  • We also need a more simplified codes

  • So we need to use the syntax of a es7

  • Called the async / await

ASYNC/AWAIT

  • async/await The syntax is a es7

  • This syntax is the callback hell ultimate solution

  • grammar:

    async function fn() {
      const res = await promise对象
    }
    
  • Syntax Specification
    1. async keyword must be written in front of a function
    2. await keyword is written in the asynchronous function inside a keyword
    -> you want to use the await keyword, the previous function must have the async keyword
    3. await key behind a word must be the object promise
    + await later with
    + we can present the results received in the inside then
    + a variable defined in the front to accept await

  • This is a special function the way

  • Objects can await a promise

  • You can write asynchronous code looks like synchronization code

  • As long as a promiser objects, then we can use async/awaitto write

    async function fn() {
      const res = new Promise(function (resolve, reject) {
        ajax({
          url: '第一个地址',
          success (res) {
            resolve(res)
          }
        })
      })
      
      // res 就可以得到请求的结果
      const res2 = new Promise(function (resolve, reject) {
        ajax({
          url: '第二个地址',
          data: { a: res.a, b: res.b },
          success (res) {
            resolve(res)
          }
        })
      })
      
      const res3 = new Promise(function (resolve, reject) {
        ajax({
          url: '第三个地址',
          data: { a: res2.a, b: res2.b },
          success (res) {
            resolve(res)
          }
        })
      })
      
      // res3 就是我们要的结果
      console.log(res3)
    }
    
    • Such asynchronous code written to look like a synchronous code
Published 10 original articles · won praise 15 · views 1971

Guess you like

Origin blog.csdn.net/Mine____/article/details/104808962