我正在嘗試使用遞回 API 呼叫構建一個 JSON 樹,但我在資料結構的流控制方面遇到了問題。如何在 BuildTree 函式堆疊結束之前阻止流?
這是部分代碼。提前致謝。
//FIRST CALL TO RETRIEVE THE ROOT
function callFW() {
d3.json(url, function(data) { //?<----- api call
Tree["uid"] = data.request.uid
Tree["hid"] = data.firmware.meta_data.hid
Tree["size"] = data.firmware.meta_data.size
Tree["children"] = [];
BuildTree(data.firmware.meta_data.included_files,Tree["children"])
//WAIT FOR BUILDTREE
console.log(Tree)
}
}
BuildTree 函式是這樣的:
async function BuildTree(included_files, fatherNode){
if( included_files.length > 0){
promises = [];
included_files.forEach(function(item) {
url = endpoint "file_object/" item "?summary=true";
promises.push(axios.get(url));
});
Promise.all(promises).then(function (results) {
results.forEach(function (response) {
var node = {}
node["uid"]= response.data.request.uid
node["hid"]= response.data.file_object.meta_data.hid
node["size"] = response.data.file_object.meta_data.size
node["children"] = []
fatherNode.push(node)
BuildTree(response.data.file_object.meta_data.included_files, node["children"])
});
});
}
}
uj5u.com熱心網友回復:
您async無緣無故地使用關鍵字,因為您沒有await在函式內部使用。你也可以使用它:)
async function BuildTree(included_files, fatherNode) {
if (included_files.length > 0) {
let promises = [];
included_files.forEach(function (item) {
url = endpoint "file_object/" item "?summary=true";
promises.push(axios.get(url));
});
const results = await Promise.all(promises);
for(let response of results){
var node = {}
node["uid"] = response.data.request.uid
node["hid"] = response.data.file_object.meta_data.hid
node["size"] = response.data.file_object.meta_data.size
node["children"] = []
fatherNode.push(node)
await BuildTree(response.data.file_object.meta_data.included_files, node["children"]);
};
}
};
然后你可以簡單地await BuildTree:
function callFW() {
d3.json(url, async function(data) {
Tree["uid"] = data.request.uid
Tree["hid"] = data.firmware.meta_data.hid
Tree["size"] = data.firmware.meta_data.size
Tree["children"] = [];
await BuildTree(data.firmware.meta_data.included_files,Tree["children"]);
console.log(Tree)
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/326799.html
標籤:javascript 异步 递归 异步等待 树
下一篇:決策樹-從特定節點洗掉
