简体   繁体   中英

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

I am building an array inside promise but I want the array to be used outside globally. My code:

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;
}

I am trying to assign the local variable AllDropdownValueslocal to a global variable AllDropdownValue . when I console log, AllDropdownValueslocal is coming ok but AllDropdownValues is not coming. How do I get the value of AllDropdownValueslocal outside the scope?

Well, you can assign it to the global variable, but you cannot use the global variable until the promise is fulfilled. It's pretty pointless to use a separate variable when you have to wait for the promise anyway. Instead, fulfill the promise with the value.

In your code, AllDropdownValueslocal is not global, it's local to your async filterAllComponent method. Instead of assigning to it from a then callback, you should just use await .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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