尝试递归调用API的异步问题

时间:2019-06-19 09:45:07

标签: javascript api loops asynchronous promise

我正在尝试根据需要执行的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);   

}

当我调用包含promise的函数(fillPropertyDict())时,我希望看到实际的字典。

0 个答案:

没有答案