promise,一個請求結束以後再發送另一個請求

異步任務1執行

runAsync1: function () {
    return new Promise(function (resolve, rej) {
      wx.request({
        url: ``,
        header: {
          'content-type': 'application/json'
        },
        method: 'POST',
        data: {},
        success(res) {
          if (res.statusCode === 200) {
            resolve(res); // 請求成功後的數據
          } else if (res.statusCode === 404) {
            utils.hideLoading();
            utils.showToast('404 頁面找不到', 'none', 3000, false);
          } else if (res.statusCode === 500) {
            utils.hideLoading();
            utils.showToast('500 服務器錯誤', 'none', 3000, false);
          } else if (res.statusCode === 503) {
            utils.hideLoading();
            utils.showToast('503 服務器開小差', 'none', 3000, false);
          }
        }
      });
    })
  },
複製代碼

異步任務2執行

runAsync2: function () {
    return new Promise(function (resolve, rej) {
      wx.request({
        url: ``,
        header: {
          'content-type': 'application/json'
        },
        method: 'POST',
        data: {},
        success(res) {
          if (res.statusCode === 200) {
            resolve(res);
          } else if (res.statusCode === 404) {
            utils.hideLoading();
            utils.showToast('404 頁面找不到', 'none', 3000, false);
          } else if (res.statusCode === 500) {
            utils.hideLoading();
            utils.showToast('500 服務器錯誤', 'none', 3000, false);
          } else if (res.statusCode === 503) {
            utils.hideLoading();
            utils.showToast('503 服務器開小差', 'none', 3000, false);
          }
        }
      });
    })
  },
複製代碼

來調用一下

fetchData: function () {
    that.runAsync1()
      .then(function (res) {
       // 處理數據1
        console.log(res.data);
        return that.runAsync2();
      })
      .then(function (res) {
        console.log(res.data);
        // 處理數據2
      })
  },複製代碼
相關文章
相關標籤/搜索