[英]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. 我在promise中构建一个数组,但希望该数组在全局范围外使用。 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 . 我正在尝试将局部变量AllDropdownValueslocal分配给全局变量AllDropdownValue 。 when I console log, AllDropdownValueslocal is coming ok but AllDropdownValues is not coming. 当我控制台日志时, AllDropdownValueslocal可以正常运行,但是AllDropdownValueslocal不可以。 How do I get the value of AllDropdownValueslocal outside the scope? 如何获得范围之外的AllDropdownValueslocal值?
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. 无论如何,当您必须等待promise时,使用单独的变量是毫无意义的。 Instead, fulfill the promise with the value. 相反,用价值实现承诺。
In your code, AllDropdownValueslocal
is not global, it's local to your async filterAllComponent
method. 在您的代码中, AllDropdownValueslocal
不是全局的,它在async filterAllComponent
方法中是本地的。 Instead of assigning to it from a then
callback, you should just use await
. 而不是从then
回调中分配它,您应该只使用await
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.