我有一个功能:
filterAllComponent(inputdata) {
let a=[], b=[],c=[];
a= this.getfilterPlaces(inputdata);
b= this.getfilterTransporter(inputdata);
c= this.getfilterVehicles(inputdata);
let getplaceArray = [],
getTransporterArray = [],
getVehicleArray = [];
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) {
var AllDropdownValues = getTransporterArray.concat(getVehicleArray).concat(getplaceArray);
console.log(AllDropdownValues);
});
}
需要将数组AllDropdownValues与 getVehicleArray , getplaceArray 和 getTransporterArray 连接起来。 在最终结果中,数组 getplaceArray 显示未定义。其余结果正确显示。
调用函数:
getfilterTransporter(autocompleteInputData) {
var k= this.checkRegex(autocompleteInputData);
this.getfilteredTransporter= this.filterTransporters(k);
return this.formatTransporterValue(this.getfilteredTransporter);
}
getfilterVehicles(autocompleteInputData) {
var k= this.checkRegex(autocompleteInputData);
this.getfilteredVehicle= this.filterVehicles(k);
return this.formatVehicleValue(this.getfilteredVehicle);
}
getfilterPlaces(autocompleteInputData) {
if (autocompleteInputData == '' || typeof(autocompleteInputData) == 'object')
return null;
this.placeData.getPlacesFromPig(autocompleteInputData)
.subscribe(response =>
return this.formatPigResponse(response);
});
}
对于 getfilterPlaces ,subscribe()用于从API调用中提取数据。但是当我调用函数filterAllComponent()时,没有填充getfilterPLaces,但是其他两个函数都正常。
答案 0 :(得分:1)
您的代码存在的问题是,订阅中的return expression
未作为return value
的{{1}}返回。这意味着,如果getfilterPlaces function
已设置且没有对象,则getfilterPlaces function
没有指定return value
。
问题是,autocompleteInputData
似乎是异步函数并返回this.placeData.getPlacesFromPig
或类似的东西。避免此问题的一种方法是使用rjxs Observable
运算符和async function
declaration。为此,您必须将await
和getfilterPlaces
标记为filterAllComponent functions
并使用async
。此外,a = await this.getfilterPlaces(inputData)
需要返回getfilterPlaces
。假设Promise
返回this.placeData.getPlacesFromPig
,代码将如下所示:
rxjs Observable
async function getfilterPlaces(autocompleteInputData) {
if (autocompleteInputData == '' || typeof(autocompleteInputData) == 'object')
return null;
return this.placeData.getPlacesFromPig(autocompleteInputData)
.toPromise()
.then(response => this.formatPigResponse(response));
}