繁体   English   中英

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

[英]Not able to assign data of a local variable inside Promise to outside variable

我在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可以正常运行,但是AllDropdownValueslocal不可以。 如何获得范围之外的AllDropdownValueslocal值?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM