解决js异步问题

万恶的后台搞了三个级联接口返回数据,让我自己拼成一个级联,搞了一天,发现它这个接口简直不忍直视,遂奋起反抗,勒令其重写接口。不过一天的纠结,并不是没有收获,get到了promise可以解决js异步的问题。用promise.then()解决了使用axios无法返回参数的问题。用法如下。

新建一个Promise构造函数,然后将这个构造函数返回

export function  getPart1(){
  var p = new Promise(function(resolve, reject){
    var productionTypeOptions=[];
    //做一些异步操作
    axios({
      method: "get",
      url: config.GET_RESOURCE_TYPE + 4,
      headers: {
        Authorization: getToken(),
        "Content-Type": "application/json"
      }
    })
      .then(function (res,callback) {
        if (res && res.data.data.resourceInfos) {
          let tempStr = res.data.data.resourceInfos[0].info;
          var tempArray;
          eval("tempArray=" + tempStr);
          var allTypeData = tempArray.productionType;
          for (let i = 0; i < tempArray.productionType.length; i++) {
            let tempList = {};
            tempList.label = tempArray.productionType[i].name;
            tempList.value = tempArray.productionType[i].name;
            productionTypeOptions.push(tempList);
            resolve(productionTypeOptions);
          }
        }
      })
      .catch(function (res) {
        this.$message({
          message: res.data.message,
          type: "warning"
        });
      });
  });
  return p;
}

大概就是以下这个结构

var p = new Promise(function(resolve, reject){
  //一些异步操作,我的是ajax   
});

然后将p返回,

 getPart1().then(function(data){
          par1 = data;
            for(var i=0;i<par1.length;i++){
              _this.productionTypeOptions.push(par1[i]);
            }
          // return getPart2();
         });

function(data)里面的data数据就是resolve(data)里面的数据。如果想继续执行getPartt2函数,可以在then里面加入return getPart2(),同理,如果在getPart2的then函数里面加入getPart3()可以继续执行getPart3()

其他详细用法请查看http://www.cnblogs.com/whybxy/p/7645578.html

猜你喜欢

转载自blog.csdn.net/xuerwang/article/details/85229629