如何分离功能

时间:2018-08-23 07:56:57

标签: javascript function

我遇到了一个问题,因为我不知道如何分离功能。我有这样的代码,我只想在then()语句中调用函数,但是我不知道如何将它们移出,因为它们具有公共变量。

.then(function(data){
  var rs = data.DL;
  var zones = [];
  var cluster = [];
  var loadStructure = [];

  function loadJsonData(rs, loadStructure) {
    //body method
    //creating zones[];
    //creating cluster[];
    return loadStructure;
  }

  function loadJsonInterZoneLinks(loadStructure, rs) {
    //body method
    //uses zones[]
    return loadStructure;
  }

  function loadJsonIntraZoneLinks(loadStructure, rs) {
    //body method
    //uses zones[] and cluster[]
    return loadStructure;
  }

  loadJsonData(loadStructure, rs);
  loadJsonInterZoneLinks(loadStructure, rs);
  return loadJsonIntraZoneLinks(loadStructure, rs);
})

每个函数将新值推送到loadStructure,最后一个返回完整的数组。由于公共变量,我不知道如何将函数移出then()。

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:-

function loadJsonData(rs) {
    //body method
    //creating loadStructure[];
    //creating zones[];
    //creating cluster[];

    var loadStructure= [];
    var zones = [];
    var cluster = [];
    return new Promise(function(resolve, reject) {
        resolve([loadStructure, zones, cluster]);
    });
}

function loadJsonInterZoneLinks(rs, loadStructure, zones, cluster) {
    //body method
    //uses zones[]
    return new Promise(function(resolve, reject) {
        resolve([loadStructure, zones, cluster]);
    });
}

function loadJsonIntraZoneLinks(rs, loadStructure, zones, cluster) {
    //body method
    //uses zones[] and cluster[]
    return new Promise(function(resolve, reject) {
        resolve([loadStructure, zones, cluster]);
    });
}


yourfunction()
.then(function(data){
  var rs = data.DL;  
  return loadJsonData(rs);
})
.then(function(data) {
   return loadJsonInterZoneLinks(rs, data[0], data[1], data[2]);
})
.then(function(data) {
   return loadJsonIntraZoneLinks(rs, data[0], data[1], data[2]);
})
.then(function(data) {
  //HERE your final DATA return from here
});