鍍金池/ 問(wèn)答/HTML/ JS如何解決異步問(wèn)題?

JS如何解決異步問(wèn)題?

圖片描述

在 if else 語(yǔ)句里面我都有異步請(qǐng)求,獲取異步請(qǐng)求的數(shù)據(jù)后設(shè)置攔截器,我的想法是有沒(méi)有辦法先把if else走完才設(shè)置攔截器,我目前的想到的辦法是用ES7 async await 但是小程序目前不支持,還有一種就是在if else里面再添加then,但是這樣要把攔截器要寫(xiě)2遍,不知道各位大神有沒(méi)有更好的解決方法?
回答
編輯回答
檸檬藍(lán)

把上面的兩個(gè)異步請(qǐng)求使用一個(gè)promise封裝一下,然后在這個(gè)promisethen里面設(shè)置攔截器:

new Promise((resolve, reject) => {
  if (!res.authSetting...) {
    fly.get('/init.ujson').then(res => {
      ...
    }).then(resolve)
  } else {
    wx.getUserInfo({
      ...
    }).then(resolve)
  }
}).then(res => {
  fly.interceptors...
})
2017年1月28日 21:43