gpt4 book ai didi

javascript - Promise 实现问题,异步无法正常工作

转载 作者:行者123 更新时间:2023-12-02 23:27:56 25 4
gpt4 key购买 nike

我正在实现一个网络应用程序,我需要以异步方式编写一些步骤。在其中一个步骤中,我调用 API 从 3D 模型中提取 id 列表,然后,我需要将其用作 Promise,以便对这些提取的 id 执行更多操作。

我在尝试实现异步时遇到麻烦,第二个函数中未正确接收 id。

我尝试实现 Promise 和回调,但没有成功。

javascript

//Create bimIdsList Promise in order to create a list with all BIM360
//elements in the model
function bimIdsList() {
self.viewer.model.getBulkProperties(ids, properties, (propResults) => {
propResults.forEach((propResult) => {
propResult.properties.forEach((property) => {
if(property.displayCategory === 'BIM 360'){
self._bimIds.push(propResult.dbId);
}
})
})
});
/*if(self._bimIds) {
resolve();
}*/

return Promise.resolve(self._bimids);

}

//Create fillEquipList function in order to fill equipment list after
//generating bimIdsList
function fillEquipList(bimIds) {
self.viewer.model.getBulkProperties(bimIds, ['Type'], (propResults) => {
propResults.forEach((propResult) => {
propResult.properties.forEach((property) => {
if(property.displayCategory === 'BIM 360') {
var foundEqIndex = self._equipList.findIndex(x => x == property.displayValue);
if(foundEqIndex >= 0) {
//Already in List, do Nothing
} else {
self._equipList.push(property.displayValue)
self._addedEquipment = true;
//Add to dropdown
const optionElement = document.createElement('option');
optionElement.value = property.displayValue;
optionElement.innerText = property.displayValue;
self._selEquipmentType.append(optionElement);

}
}
})
})



});
//Resolve after callback
return Promise.resolve(self._addedEquipment);

}


//Now execute both functions
bimIdsList()
.then(success => {
console.log('bimIds length: ');
console.log( JSON.parse(JSON.stringify(success)) )
return fillEquipList(success)
})
.then(success => this.fillDictionaries());


console.log(this._bimIds);

我想使用来自初始 Promise (bimIds) 的适当给定参数来执行第二个函数 (fillEquipList)

最佳答案

return Promise.resolve(self._bimids);

您正在创建一个已解决的 Promise...但您是在异步函数(self.viewer.model.getBulkProperties触发)后立即执行的。

您需要创建一个立即返回的 promise ,但在您实际拥有数据之前不会解析:

return new Promise( function (resolve) {
// self.viewer.model.getBulkProperties goes here
// resolve(data) goes *inside the callback*
})

关于javascript - Promise 实现问题,异步无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56651756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com