无法将Promise中的局部变量数据分配给外部变量

时间:2018-03-09 12:03:15

标签: javascript angular promise

我正在构建一个承诺内的数组,但我希望数组在全局范围内使用。我的代码:

AllDropdownValues: any[];

async filterAllComponent(inputdata) {
     let a=[], b=[],c=[];
    a=  await this.getfilterPlaces(inputdata);
    b= this.getfilterTransporter(inputdata);
    c= this.getfilterVehicles(inputdata);
    let getplaceArray = [],
  getTransporterArray = [],
  getVehicleArray = [];
  var AllDropdownValueslocal:any[];

let getPlacePromise = function () {
  const self = this;
  return new Promise(function (resolve, reject) {
    getplaceArray = a;
    resolve("got places\n");
  });
};

let getTransporterPromise = function (message) {
  const self = this;
  return new Promise(function (resolve, reject) {
    getTransporterArray =  b;
    resolve(message + "got Transporter");

  });
};

let getVehiclePromise = function (message) {
  const self = this;
  return new Promise(function (resolve, reject) {
    getVehicleArray = c;
    resolve(message + "got vehicle");

  });
};

getPlacePromise().then(function (result) {
  return getTransporterPromise(result);
}).then(function (result) {
  return getVehiclePromise(result);
}).then(function (result) {
  AllDropdownValueslocal = getTransporterArray.concat(getVehicleArray).concat(getplaceArray);

}).catch(function(){
  console.log("error");
});
this.AllDropdownValues =  AllDropdownValueslocal;
}

我正在尝试将局部变量 AllDropdownValueslocal 分配给全局变量 AllDropdownValue 。当我登录日志时, AllDropdownValueslocal 即将推出,但 AllDropdownValues 未来。如何在范围之外获取AllDropdownValueslocal的值?

1 个答案:

答案 0 :(得分:0)

好吧,您可以将其分配给全局变量,但在履行承诺之前不能使用全局变量。无论如何,当你必须等待承诺时,使用单独的变量是毫无意义的。相反,履行价值承诺。

在您的代码中,AllDropdownValueslocal不是全局的,它是您async filterAllComponent方法的本地代码。您应该只使用then,而不是从await回调分配给它。