【问题标题】:Running viewer.getProperties for multiple elements in parallel and then handling the result并行运行多个元素的 viewer.getProperties,然后处理结果
【发布时间】:2017-08-16 01:37:50
【问题描述】:

我正在使用viewer.getProperties(dbId, onSuccessCallback, onErrorCallback) 方法来获取查看器中对象的属性。我想为所有选定的对象运行该方法,为每个对象提取属性的子集,并将子集呈现在表中。

var subsets = [];
var selectFunctions = [];
handleSelection(selection, addProps, onError);

function handleSelection(selection, onSuccess, onError) {
  for (var i = 0; i < selection.length; i++)
    selectFunctions.push(_viewer.getProperties(selection[i], onSuccess, onError));
}

function addProps(data) { 
  var props = [];
  for (var prop in data.properties) {
    //Add property to props if some condition is true...
  }

  subsets.push(props);
}

Promise.all(_selectFunctions).then(function () {
  console.log("Handled all selections");
  //Add subsets to table...
}).catch(function (error) {
  console.log("ERRROR");
});

由于 getProperties 是异步运行的,我无法在更新表之前等待所有对象。该表一次更新一个对象,我们宁愿一次更新所有对象。阻塞 IO 不是问题。

正如可能显示的那样,我一直在研究 bluebird.js 中的 Promise.all(),以控制执行并等待所有 getProperties 调用返回,但到目前为止没有成功。

问候, 托瑞斯

【问题讨论】:

    标签: node.js autodesk-forge autodesk-viewer


    【解决方案1】:

    这个问题与查看器的使用完全无关,您需要查找一些有关如何使用 Promises 的文档才能等待并行完成多个请求。

    这里有一些可能对你有帮助的伪代码(ES6 语法),为了清楚起见,我跳过了错误处理:

    // wrap get the async method in a promise so you can wait its completion
    const getPropertiesAsync = (id) => {
       return new Promise((resolve, reject) => {
    
         _viewer.getProperties(id, (result) => {
    
            resolve(result)
    
          }, (error) => {
    
            reject(error)
          })
       })
    } 
    
    //create an array of asynchronous tasks for each component you want to get props on
    const propTasks = componentIds.map((id) => {
    
      return getPropertiesAsync(id)
    })
    
    //promise version 
    Promise.all(propTasks).then((results) => {
    
     //populate table with results
    })
    
    //OR async ES7 syntax
    const results = await Promise.all(propTasks)
    
    //populate table with results
    

    这是我写的一篇关于在查看器中使用 async/await 的文章,但由于主题更广泛,您应该能够通过自己查看网络找到更多文档:

    Getting rid of JavaScript callbacks using async/await

    希望有帮助

    【讨论】:

    • 您能否接受回复作为答案或解释它如何无法解决您的问题?谢谢
    • 谢谢你,菲利普!这很好用,我认为 getProperties 方法有问题,但结果我误解了 resolve 和 reject 的使用。
    猜你喜欢
    • 2012-11-09
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多