Promise对axios多个请求的处理

文章参考

http://es6.ruanyifeng.com/#docs/promise

http://blog.csdn.net/quanquanxiu/article/details/76718468

Promise对象是ES6的内容,我们可以使用babel做一个转换,基本语法如下:

var promise = new Promise(function(resolve, reject) {
  // ... some code

  if (/* 异步操作成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});
//then方法的第一个参数是resolved状态的回调函数,第二个参数(可选)是rejected状态的回调函数。
promise.then(function funcA(comments) {
  console.log("resolved: ", comments);
}, function funcB(err){
  console.log("rejected: ", err);
});
var promise = new Promise(function(resolve, reject) {
  throw new Error('test');
});
promise.catch(function(error) {
  console.log(error);
});

多个异步请求全部成功之后处理的业务请求

/**
* 传入多个promise的值,当请求成功之后统一反馈,做逻辑处理
* */
allPromise: function(promise1,promise2){
// 将数组对象转为了数组
  var userPromise = Array.prototype.slice.apply(arguments);
  console.dir(userPromise);
// 添加断点调试
  debugger
  var promiseObj = new Promise(function(resolve, reject){
	  axios.all(userPromise).then(axios.spread(function () {
		  resolve(arguments);
	  }),function(){
		  reject(arguments);
	  });
  });
  return promiseObj;
},

 使用案例

//  获取工厂的信息
  var getorgInfoPromise = getData.getRestful("getWarehousesByFacotryid", {id: whOrgId});
  //拼装查询参数
  var queryParam = {
	status: nodeObj.status,
	whOrgId: whOrgId
  }
  // 根据工厂ID 获取下面的库房信息列表
  var getWarehousesByFacotryidPromise = getData.postRestful("searchWarehouseInfo", {
	pageSize: pageSize,
	pageNum: current
  }, queryParam);
  // 当两个请求同时返回之后触发的事件
  getData.allPromise(getorgInfoPromise, getWarehousesByFacotryidPromise).then(function (responseObj) {
	var getorgInfoPromiseRes = responseObj[0];
	var getWarehousesByFacotryidPromiseRes = responseObj[1];
	// 状态码为0 表示请求成功
	if (getorgInfoPromiseRes.data.resultCode == 0 && getWarehousesByFacotryidPromiseRes.data.resultCode == 0) {
	  var treeInfo = {
		// 点击仓库类型
		type: "org",
		// 列表信息
		listInfo: getWarehousesByFacotryidPromiseRes.data,
		// 详细信息
		detailInfo: getorgInfoPromiseRes.data
	  }
	  that.totalNum = getWarehousesByFacotryidPromiseRes.data.totalNum;

	  that.treeClickAction(treeInfo);
	}
  });

相关推荐