我正在尝试根据我必须执行的 API 调用构建一个字典,为每个调用为 API 提供一个给定的 id。在这个过程之后,我需要对生成的字典进行操作。问题是我无法让异步正常工作。
我试图实现 Promises,但没有成功。
var self = this;
function fillPropertyDict(){
var itemsProcessed = 0;
return new Promise(function(resolve) {
//Loop for every ID
self._bimIds.forEach((bimId) => {
itemsProcessed++;
//Calling the API
self.viewer.model.getProperties(bimId, (resultado) => {
resultado.properties.forEach((prop) => {
if(prop.displayName == 'Type' && prop.displayCategory == 'BIM 360') {
var foundIndex = self._propertyDictionary.findIndex(x => x.dbId == bimId)
if (foundIndex > 0){
self._propertyDictionary[foundIndex].equipment = prop.displayValue
} else {
var el = new Object();
el.dbId = bimId;
el.equipment = prop.displayValue;
el.sap = '';
self._propertyDictionary.push(el);
}
} else if (prop.displayName == 'Description' && prop.displayCategory == 'BIM 360') {
var foundIndex = self._propertyDictionary.findIndex(x => x.dbId == bimId)
if (foundIndex > 0){
self._propertyDictionary[foundIndex].sap = prop.displayValue
} else {
var el = new Object();
el.dbId = bimId;
el.equipment = '';
el.sap = prop.displayValue;
self._propertyDictionary.push(el);
}
}
})
})
//If count reaches array length, resolve Promise
if(itemsProcessed == self._bimIds.length){
//Resolve inside callback
resolve(self._propertyDictionary);
}
})
});
}
//Call function
fillPropertyDict().
then(function(result) {
//Let's print the dictionary
console.log('Lets see self._propertyDictionary');
console.log( JSON.parse(JSON.stringify(result)) );
console.log(result);
}
当我调用包含承诺 (fillPropertyDict()) 的函数时,我希望看到实际的字典。