js中回調函數,promise 以及 async/await 的對比用法 對比!!!


在編程項目中,我們常需要用到回調的做法來實現部分功能,那么在js中我們有哪些方法來實現回調的?

方法1:回調函數

首先要定義這個函數,然后才能利用回調函數來調用!

login: function (fn) {
    var app = getApp()
      wx.login({
        success: res => {
          let code = res.code;
          wx.getSetting({
            success: res => {
              if (res.authSetting['scope.userInfo']) {
                wx.getUserInfo({
                  success: res => {
                    console.log(res)
                    var inviteUid = wx.getStorageSync('inviteUid')
                    let dataMap = new Map();
                    dataMap.set('from', 3);
                    dataMap.set('superiorId', inviteUid);
                    dataMap.set('code', code);
                    dataMap.set('encryptedData', res.encryptedData);
                    dataMap.set('iv', res.iv);
                    dataMap.set('scene', 6);
                    app.get_sign(dataMap, function (...reo) {
                      let [time, version, client, sign] = reo;
                      wx.request({
                        url: app.globalData.url + '/api3_1/WxLogin/login',
                        data: {
                          time,
                          version,
                          client,
                          sign,
                          from: 3,
                          superiorId: inviteUid,
                          code,
                          encryptedData: res.encryptedData,
                          iv: res.iv,
                          scene: 6
                        },
                        method: 'POST',
                        header: {
                          'content-type': 'application/x-www-form-urlencoded'
                        },
                        success: function (res) {
                          console.log(res)
                          var identity_id = res.data.data.identity_id
                          wx.setStorageSync('identity_id', identity_id)
                          if (res) {
                             fn(res) 
                          }
                        }
                      })
                    })
                  }
                })
              }
            }
          })
        }
    })

  },

調用

app.login((res)=>{
  
})

方法2:es6的 promise 

同樣,我們先定義一個帶有promise的函數

 login: function (fn) {
    var app = getApp()
    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          let code = res.code;
          wx.getSetting({
            success: res => {
              if (res.authSetting['scope.userInfo']) {
                wx.getUserInfo({
                  success: res => {
                    console.log(res)
                    var inviteUid = wx.getStorageSync('inviteUid')
                    let dataMap = new Map();
                    dataMap.set('from', 3);
                    dataMap.set('superiorId', inviteUid);
                    dataMap.set('code', code);
                    dataMap.set('encryptedData', res.encryptedData);
                    dataMap.set('iv', res.iv);
                    dataMap.set('scene', 6);
                    app.get_sign(dataMap, function (...reo) {
                      let [time, version, client, sign] = reo;
                      wx.request({
                        url: app.globalData.url + '/api3_1/WxLogin/login',
                        data: {
                          time,
                          version,
                          client,
                          sign,
                          from: 3,
                          superiorId: inviteUid,
                          code,
                          encryptedData: res.encryptedData,
                          iv: res.iv,
                          scene: 6
                        },
                        method: 'POST',
                        header: {
                          'content-type': 'application/x-www-form-urlencoded'
                        },
                        success: function (res) {
                          console.log(res)
                          var identity_id = res.data.data.identity_id
                          wx.setStorageSync('identity_id', identity_id)
                          if (res) {
 resolve(res)
                          }
                        }
                      })
                      var userInfo = res.userInfo
                      wx.setStorageSync('userInfo', userInfo)
                    })
                  }
                })
              }
            }
          })
        }
      })
    })

  },

來來來,這么調用,這里主要是最后通過.then來進行回調的寫法

app.login().then((res) => {
       console.log(res);
})

方法3:es6中async / await 

同樣,還是先定義函數,這個和方法2其實是一樣的定義方法,還是用promise來進行定義一個返回,只是調用這個函數的時候不一樣。

login: function (fn) {
    var app = getApp()
    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          let code = res.code;
          wx.getSetting({
            success: res => {
              if (res.authSetting['scope.userInfo']) {
                wx.getUserInfo({
                  success: res => {
                    console.log(res)
                    var inviteUid = wx.getStorageSync('inviteUid')
                    let dataMap = new Map();
                    dataMap.set('from', 3);
                    dataMap.set('superiorId', inviteUid);
                    dataMap.set('code', code);
                    dataMap.set('encryptedData', res.encryptedData);
                    dataMap.set('iv', res.iv);
                    dataMap.set('scene', 6);
                    app.get_sign(dataMap, function (...reo) {
                      let [time, version, client, sign] = reo;
                      wx.request({
                        url: app.globalData.url + '/api3_1/WxLogin/login',
                        data: {
                          time,
                          version,
                          client,
                          sign,
                          from: 3,
                          superiorId: inviteUid,
                          code,
                          encryptedData: res.encryptedData,
                          iv: res.iv,
                          scene: 6
                        },
                        method: 'POST',
                        header: {
                          'content-type': 'application/x-www-form-urlencoded'
                        },
                        success: function (res) {
                          console.log(res)
                          var identity_id = res.data.data.identity_id
                          wx.setStorageSync('identity_id', identity_id)
                          if (res) {
                     resolve(res)
                          }
                        }
                      })
                      var userInfo = res.userInfo
                      wx.setStorageSync('userInfo', userInfo)
                    })
                  }
                })
              }
            }
          })
        }
      })
    })

  },

咱再來進行調用,這個理論上,你要自己在定義一個新的函數,然后才能用async/await ,可以理解為 await 的等一等,然后就能拿到app.login的返回值,這個方法,在多重回調中就能發揮很大的作用。

async onGotUserInfo(e) {
    let res = await app.login();
    console.log(res);
}

小結:

如果我們只有一次回調,我們可以用回調函數,也可以用promise,然后用.then來獲取值。

如果有多次回掉,那么我們推薦用方法3,這個終極的方案來進行獲取回調的值。

如何一個函數返回的是promise對象,則調用這個函數即可用.then()來拿到回調的值。

如果一個函數本身返回的是promise對象,那么我們除了用.then()來拿到回調的值,也可以用await  來等一等,然后就能拿到這個回調的值,當然前提是本身外面需要async這個值來進行修飾!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM