js promise, async asynchronous data chain acquisition --- callback hell

Background: When shopping, you want to drink milk tea, eat hot pot, and do manicures. But you want to eat hot pot first, then drink milk tea, and then go for manicure.

In es5, asynchronous data will be obtained through the callback function. There will be the following way of writing

//获取食品的方法
        function getTea(fn) {
            setTimeout(() => {
                fn('奶茶')
            }, 500)
        }
        function getHotPot(fn) {
            setTimeout(() => {
                fn('火锅')
            }, 2000)
        }
        function getBe(fn) {
            setTimeout(() => {
                fn('美甲')
            }, 1000)
        }
        //调用获取方法
        getTea((data) => console.log(data));
        getHotPot((data) => console.log(data));
        //如果想先吃火锅再吃奶茶就得
        getHotPot(function (data) {
            console.log(data)
            getTea(function (data) {
                console.log(data)
                getBe(function (data) {
                    console.log(data)
                })
            })
        })
        

This is difficult to maintain. To control the order, nesting is required. If a bug occurs, it is difficult to fix. After ES6 has promises, there is no need for callback functions to obtain asynchronous data. Next, we will modify the above code.

// promise对象 --resolve可以将异步数据传出来
      let p = new Promise(function (resolve) {
          resolve(data)
      })
      p.then((data) => {
          console.log(data)
      })
      //改造上述问题代码
      function getTea() {
          return new Promise((resolve) => {
              resolve('奶茶')
          })
      }
      function getHotPot() {
          return new Promise((resolve) => {
              setTimeout(() => {
                  resolve('火锅')
              }, 2000)
          })
      }
      function getBe() {
          return new Promise((resolve) => {
              resolve('美甲')
          })
      }
      //先吃火锅再吃奶茶再做美甲
      getHotPot().then(function (data) {
          console.log(data);
          return getTea()
      }).then(function (data) {
          console.log(data);
          return getBe()
      }).then(function (data) {
          console.log(data);
      })

Next, we use the async function to implement. There is await in the async function to obtain the returned asynchronous data. In addition, the return value of the async function is a promise object

//用async函数操作
        async function getData(){
            let HotPot = await getHotPot();
            console.log(HotPot);
            let Tea = await getTea();
            console.log(Tea);
            let be = await getBe();
            console.log(be)
        }
        getData();
        ```
        
        

Guess you like

Origin blog.csdn.net/DragonOfMoon/article/details/124117515