2017-03-23 47 views
0

我正在使用viewer.getProperties(dbId, onSuccessCallback, onErrorCallback)方法來獲取查看器中對象的屬性。我想爲所有選定對象運行該方法,爲每個對象提取屬性的子集,並將子集呈現在表中。爲多個元素並行運行viewer.getProperties,然後處理結果

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調用返回,但到目前爲止失敗。

問候, Torjus

回答

1

這個問題純屬無關使用瀏覽器,你將需要尋找關於如何使用的承諾,以等待並行多個請求的完成一些文檔。

這裏,我跳過錯誤爲了清楚起見處理一些僞代碼,可以幫助你(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 

這裏是一個文章,我寫了一篇關於使用異步/等待與觀衆,但由於話題要廣泛得多,你應該能夠通過自己尋找在網上找了很多更多的文檔:

Getting rid of JavaScript callbacks using async/await

希望幫助

+0

您能否接受答覆作爲答覆或解釋它如何解決您的問題?謝謝 –

+0

謝謝Philippe!這工作完美,我認爲getProperties方法有問題,但事實證明我誤解了解析和拒絕的使用。 – torjuss

相關問題