渣渣前端在jq项目中实现简单的promise&async await

171 阅读1分钟

1.先实现promise咯咯

function thcatPromise(exec, _next) {
  var _PENDING = 'pending'; //初始状态
  var _FULFILLED = 'fulfilled'; // 成功状态
  var _REJECTED = 'rejected'; // 成功

  function res(data) {
    thcatPromise.status = _FULFILLED

    for (var x = 0; x < this.successList.length; x++) {
      this.successList[x](data)
    }
    this.finallyExec()
    //如果在async中就执行next 
    //这个是在async中抛出的prototype
    if (this.async._next) this.async._next()
  }
  function fail(data) {
    thcatPromise.status = _REJECTED
    for (var x = 0; x < this.failList.length; x++) {
      this.failList[x](data)
    }
    this.finallyExec()
  }

  exec(res.bind(this), fail.bind(this))
}

2.wrapPromise 这是为了融合 promise 和 async的方法。。

function wrapPromise(obj) {
    var preUrl = routeDeviceAlarm;
    var static = { 'type': 'GET', 'data': {}, 'url': '', showLoading: false }
    if (typeof obj === 'object') {
        for (var val in static) {
            if (!obj[val]) {
                obj[val] = static[val]
            }
        }
    } else if (typeof obj !== 'function') {
        obj = static
    }

    return function (_this) {
        if (_this) {
            thcatPromise.prototype.async = _this
        } else {
            thcatPromise.prototype.async = {}
        } //继承前面生成的async方法和变量

        return new thcatPromise(function (res, rej) {
            if (typeof obj === 'function') {
                var _nextData = JSON.parse(JSON.stringify(_this.nextData))
                res(_nextData) //数据写入下入一次nextData
                obj(_nextData) //获取上一次的数据                           
                return
            }

            $.ajax({
                type: obj.type,
                url: obj.url,
                dataType: "json",
                data: obj.data,
                success: function (result) {
                    if (result.isSuccess) {
                        res(result)
                    } else {
                        res(result)
                    }
                },
                error: function (err) {
                    console.log(err)
                    res(err)
                }
            });

        })
    }.bind(obj)
}

3.async,await

//async
function Tasync(run) {
  run.call(this)
}
Tasync.prototype.asyncRunList = []
Tasync.prototype.Tawait = function (fun) {
  this.asyncRunList.push(fun)
}
Tasync.prototype.nextData = null
Tasync.prototype.cur = 0;
Tasync.prototype._run = function (data) {
  var nowFUn = this.asyncRunList[this.cur]
  if (!nowFUn) return
  var maybePromise = nowFUn(this)//传入当前的this,用于在wrapPromise中绑定
  //判断是不是promise
  if (maybePromise && maybePromise.then) {
    maybePromise.then(function (data) {
      this.nextData = data
    }.bind(this))
  }
}
Tasync.prototype._next = function () {
  this.cur += 1
  if (this.asyncRunList[this.cur]) {
    //深拷贝,因为nextData会改变的
    var retunData = JSON.parse(JSON.stringify(this.nextData))
    this._run(retunData)
  }
}


4.最后效果


  //获取ajax 获取的数据
  var afterGetGoodsSpecies = wrapPromise(function (data) {
    if (data.isSuccess) {
      var ds = data.returnValue;
      //筛选
      watchObj.setGoodsSpecies.val = ds
      //editor
      watchObj.setGoodsSpeciesEditor.val = ds

    } else {
      layer.msg(data.message);
      return false;
    }
  })
  
  //获取数据
  var getGoodsSpecies = wrapPromise({
    url:url,
    type:"post",
    data:data
})
  
 new Tasync(function () {
    this.Tawait(getGoodsSpecies)
    this.Tawait(afterGetGoodsSpecies)
    this.Tawait(getGoodsSpecies)
    this.Tawait(afterGetGoodsSpecies)
    this.Tawait(getGoodsSpecies)
    this.Tawait(afterGetGoodsSpecies)
    this._run()
 })