同步等待方法

时间:2022-04-23
本文章向大家介绍同步等待方法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
function waitVar(key,varb, fun) {      //等待指定变量,返回:-1:无数据,继续等待 -2:超时 1:成功。fun不支持参数
  if (!cnt2[key]) {
    cnt2[key] = 1
  }
  else {
    cnt2[key]++
  }
  if (!varb || varb.length == 0) {
    if (cnt2[key] > 10) {      //超时,由于都是异步操作,相互依赖的变量会同时判断,所以这个时间是最大的
      wx.showToast({
        title: '无法获取数据!',
        image: "/remind.png",
        duration: 3000
      })
      return -2
    }
    else {
      console.log("等待变量同步" + key, varb)
      wx.showToast({
        title: '正在下载数据!',
        image: "/remind.png",
        duration: 500
      })

      if (arguments.length == 3)  //正常状态,fun没有参数
        setTimeout(fun, 500)

      //对于onLoad无法使用,因为他的参数无法像普通参数一样处理  
      if (arguments.length == 4)  //正常状态,fun有1个参数,arguments不能按照数组来处理,不能用slice,所以逐个处理
      {
        console.log("参数",arguments,arguments[3])
        setTimeout(fun, 500, arguments[3]) //arguments:0,1,2:3个参数。3:传递给fun的参数。setTimeout(回调函数,时间,参数1,...,参数n)
      }

      return -1
    }
  }
  return 1
}