qq_40665861
寂寞花如雪
采纳率0%
2020-07-14 16:18

js如何在当前函数中执行另一个函数,并等待另一个函数执行结束。

js如何在当前函数中执行另一个函数,并等待另一个函数执行结束

var baseURL = require('./api.js');
var sm2 = require('./sm2.js');
var appJs;
// 展示进度条的网络请求
// url:网络请求的url
// params:请求参数
// message:进度条的提示信息
// methods:请求方式
// hideLoad:隐藏wx.showLoading
// hideToast:隐藏wx.showToast
//用于生成uuid
function S4() {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function guid() {
  return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

function objKeySort(obj) { //排序的函数
  var newkey = Object.keys(obj).sort();
  //先用Object内置类的keys方法获取要排序对象的属性名,再利用Array原型上的sort方法对获取的属性名进行排序,newkey是一个数组
  var newObj = {}; //创建一个新的对象,用于存放排好序的键值对
  for (var i = 0; i < newkey.length; i++) { //遍历newkey数组
    newObj[newkey[i]] = obj[newkey[i]]; //向新创建的对象中按照排好的顺序依次增加键值对
  }
  return newObj; //返回排好序的新对象
}

function timest() {
  var tmp = Date.parse(new Date()).toString();
  tmp = tmp.substr(0, 10);
  return tmp;
}

var uuid;
var token = "";
var _token_ = "";
let superPrivateKey = sm2.superPrivateKey;
let privateKey = "";
const rsa = require('../utils/cryptojs-master/cryptojs.js');
const Encrypt = require('../utils/jsencrypt.min.js');
let encryptor = new Encrypt.JSEncrypt();
encryptor.setPrivateKey(superPrivateKey); // 设置私钥     

// function getResult(callback, callback1) {
//   if (!privateKey) {
//     callback()
//     debugger
//   } else {
//     callback1()
//   }
// }
// getResult(getA, requestLoading);

function getA() {
  wx.request({
    url: baseURL.baseURL + 'api/services/app/Setting/GetCerPriKeyAsync',
    data: '',
    header: {},
    method: 'Get',
    success: function(res) {
      console.log(res)
      let array = res.data.Result.Data;
      let sourcePrivate = '';
      for (let a = 0; a < array.length; a++) {
        sourcePrivate += encryptor.decrypt(array[a]);
      }
      console.log("原始私钥" + sourcePrivate);
      encryptor.setPrivateKey(sourcePrivate);
      privateKey = sourcePrivate;
      debugger
      // requestLoading()
      // getHomeSetting()
    },
    fail: function(res) {
      console.log(res)
    },
    complete: function(res) {},
  })
}

function requestLoading(url, params, message, methods, hideLoad, hideToast) {
  if (!appJs) {
    appJs = getApp();
  }
  return new Promise(function(resolve, reject) {
    if (!privateKey) {
      getA()
      debugger
      reject()
    }
    var method = methods || "GET";
    params = params || {};
    params.MpContentType = 1;
    if (!hideLoad) {
      if (method == "POST") {
        if (message != "") {
          wx.showLoading({
            title: message,
            mask: true
          })
        } else {
          wx.showLoading({
            title: '数据加载中',
            mask: true
          });
        }
      }
    }
    if (url.substring(0, 1) == '/') {
      url = url.substr(1);
    }
    // token存在直接使用,不存在为空
    if (appJs) {
      token = appJs.globalData.token;
      appJs.globalData.privateKey = privateKey;
      if (!token) {
        token = wx.getStorageSync('token') || wx.getStorageSync('token');
        appJs.globalData.token = token;
      }
      _token_ = token;
    } else {
      token = wx.getStorageSync('token') || wx.getStorageSync('token');
      _token_ = token;
    }
    // url拼接token和__shop__
    let __shop__ = wx.getStorageSync('organizationid') || '';
    if (url.lastIndexOf("?") == -1) {
      url = url + '?_token_=' + _token_ + '&__shop__=' + __shop__
    } else {
      url = url + '&_token_=' + _token_ + '&__shop__=' + __shop__
    }
    if (method == "GET") {
      params.timestamp = timest();
      params = objKeySort(params);
      let str = Object.keys(params).map(function(key) {
        return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(params[key]));
      }).join('&');
      str = '_token_=' + _token_ + '&__shop__=' + __shop__ + '&' + str;
      let sha256sign = encryptor.sign(str, rsa.Crypto.SHA256, "SHA256");
      sha256sign = encodeURIComponent(sha256sign);
      params.sign = sha256sign;
    }
    if (method == "POST" || method == "PUT") {
      var aa = JSON.stringify(params);
      let str = '_token_=' + _token_ + '&__shop__=' + __shop__ + '&timestamp=' + timest() + aa;
      let sha256sign = encryptor.sign(str, rsa.Crypto.SHA256, "SHA256")
      sha256sign = encodeURIComponent(sha256sign);
      url = url + '&timestamp=' + timest() + '&sign=' + sha256sign;
    }
    if (method == "DELETE") {
      let index = url.lastIndexOf("?");
      let str = url.substring(index + 1, url.length) + '&timestamp=' + timest() + JSON.stringify(params);
      let sha256sign = encryptor.sign(str, rsa.Crypto.SHA256, "SHA256")
      sha256sign = encodeURIComponent(sha256sign);
      url = url + '&timestamp=' + timest() + '&sign=' + sha256sign;
    }
    // uuid存在直接使用,否则存储本地使用新的
    uuid = wx.getStorageSync('uuid');
    if (!uuid) {
      uuid = guid();
      wx.setStorageSync('uuid', uuid);
    }
    var Device = "device/" + uuid
    if (wx.canIUse('getAccountInfoSync')) {
      const accountInfo = wx.getAccountInfoSync();
      var MicroApp = accountInfo.miniProgram.version;
      if (MicroApp) {
        Device = Device + " microapp/" + MicroApp
      }
    }
    wx.request({
      url: baseURL.baseURL + url,
      data: params,
      header: {
        'Content-Type': 'application/json',
        'Abp.Tenantld': '2',
        'authorization': token,
        "Device": Device
      },
      method: method,
      success: function(res) {
        if (message != "") {
          wx.hideLoading()
        } else {
          wx.hideLoading()
        }
        //请求成功
        //判断状态码---errCode状态根据后端定义来判断
        if (res.statusCode == 200) {
          if (res.data.Result.Code == 0) {
            resolve(res);
            wx.hideLoading();
          } else if (res.data.Result.Code == 401 && url != 'api/services/app/MemberSession/GetLoginState') {
            wx.hideLoading();
            if (!hideToast) {
              setTimeout(function() {
                wx.showToast({
                  title: '登录已过期,请重新登录',
                  icon: 'none',
                  duration: 1000,
                  mask: true
                })
              }, 500)
            }
            wx.removeStorageSync('OpenId');
            wx.removeStorageSync('token');
            appJs.globalData.token = ""
            wx.removeStorageSync('MemberId');
            reject();
            wx.reLaunch({
              url: '/pages/member/loginAndRegister/loginAndRegister',
            })
          } else if (res.data.Result.Code == 404 || res.data.Result.Code == 101) {
            wx.hideLoading();
            resolve(res);
          } else {
            wx.hideLoading();
            if (!hideToast) {
              setTimeout(function() {
                wx.showToast({
                  title: res.data.Result.Message,
                  icon: 'none',
                  duration: 2000,
                  mask: true
                })
              }, 500)
            }
            resolve(res);
          }
          wx.hideLoading();
        } else if (res.statusCode == 401) {
          wx.hideLoading();
          if (!hideToast) {
            setTimeout(function() {
              wx.showToast({
                title: '登录已过期,请重新登录',
                icon: 'none',
                duration: 2000,
                mask: true
              })
            }, 500)
          }
          wx.removeStorageSync('OpenId');
          wx.removeStorageSync('token');
          appJs.globalData.token = ""
          wx.removeStorageSync('skin');
          wx.removeStorageSync('Router');
          wx.removeStorageSync('Url');
          reject();
          wx.reLaunch({
            url: '/pages/member/loginAndRegister/loginAndRegister',
          })
        } else {
          wx.hideLoading();
          wx.hideToast();
          if (res.data.Error.Message) {
            if (!hideToast) {
              wx.showToast({
                title: res.data.Error.Message,
                icon: 'none',
                duration: 2000,
                mask: true
              })
            }
          } else {
            if (!hideToast) {
              setTimeout(function() {
                wx.showToast({
                  title: '请求异常',
                  icon: 'none',
                  mask: true
                })
              }, 500)
            }
          }
          //其他异常
          reject('运行时错误,请稍后再试');
        }
      },
      fail: function(res) {
        wx.hideLoading();
        if (!hideToast) {
          setTimeout(function() {
            wx.showToast({
              title: '请求异常',
              icon: 'none',
              mask: true
            })
          }, 500)
        }
        //请求失败
        reject(res);
      },
      complete: function(res) {},
    })
  })
}

module.exports = {
  requestLoading: requestLoading
}

需求先执行getA在执行requestLoading

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • qq_39364586 前端探索者 9月前

    使用es6 的await/async

    点赞 评论 复制链接分享

为你推荐