【发布时间】:2020-11-28 17:28:55
【问题描述】:
getTreeData(): Promise<Node[]>{
let customerUID;
const promises: Promise<any>[] = [];
const tree: Node[] = [];
promises.push(this.firestore.collection('activities').doc(this.codeValue).get().toPromise().then(doc => {
customerUID = doc.data().customerUID;
promises.push(this.firestore.collection('customers').doc(customerUID).collection('order').get().toPromise().then(task => {
task.forEach( doc1 => {
const node = {name: doc1.id, children: [], parent: null};
promises.push(this.getChildren(doc1, node).then( children => {
node.children = children;
console.log("hi");
tree.push(node);
}));
});
}));
}));
return Promise.all(promises).then(() => {
return tree;
});
}
getChildren(doc: firebase.firestore.QueryDocumentSnapshot<firebase.firestore.DocumentData>, parentNode: Node): Promise<Node[]>{
const promises: Promise<any>[] = [];
const tree: Node[] = [];
promises.push(doc.ref.collection('children').get().then(task => {
task.forEach(doc1 => {
const node = {name: doc1.id, children: [], parent: parentNode};
promises.push(this.getChildren(doc1, node).then( children => {
node.children = children;
console.log("hi");
tree.push(node);
}));
});
}));
console.log(promises);
return Promise.all(promises).then(() => {
return tree;
});
}
getTreeData() 应该返回 Node[](自定义界面中的节点),该节点会转到材质树 主函数返回一个空数组(promise.all() 不能正常工作)。
也许我错过了 promises.all 的一些内容?
也许我不能返回 promise.all().then(.....)?
【问题讨论】:
-
您似乎在最初添加到数组中的 Promise 中向 Promise 数组中添加了更多 Promise。这似乎是一个糟糕的举动。
-
请编辑问题以准确描述您希望此代码执行的操作。这段代码“正常工作”意味着什么?您在这里有数据库查询,但我们看不到您正在使用的数据。
-
我通过这个函数编辑了我的愿望
-
你只有一个简单的竞争条件。基本上,被推入你的承诺数组的唯一承诺是外循环。因为当内部循环推送完成时,promise.all 已经被调用了。
-
那是有道理的@Keith 你能写一个解决方案吗?!
标签: javascript typescript firebase asynchronous promise