Javascript Firebase添加内部for循环
我正在地图中运行firebaseJavascript Firebase添加内部for循环,javascript,firebase,google-cloud-firestore,Javascript,Firebase,Google Cloud Firestore,我正在地图中运行firebaseadd。问题是我需要返回新添加文档的引用,但看起来它在之前进入下一个迭代。然后运行当前迭代的。我尝试了wait,但无法使其正常工作 taskContexts = taskContexts.map(taskContext => { const found = contexts.find(el => el.name === taskContext); // If context exists, return reference
add
。问题是我需要返回新添加文档的引用,但看起来它在之前进入下一个迭代。然后运行当前迭代的。我尝试了wait
,但无法使其正常工作
taskContexts = taskContexts.map(taskContext => {
const found = contexts.find(el => el.name === taskContext);
// If context exists, return reference
if (found) {
return this.props.firebase.db.doc("/contexts/" + found.uid);
} else {
// If it doesn't, create new context
// The add works, but it looks like the .then is only ran after the iteration has finished
this.props.firebase.contexts().add({
created: this.props.firebase.fieldValue.serverTimestamp(),
name: taskContext,
})
// Then return reference
.then((response) => {
console.log("New context added with id:");
console.log(response.id);
return this.props.firebase.db.doc("/contexts/" + response.id);
})
.catch(function(error) {
console.error("Error adding new context: ", error);
});
}
});
看看Promise.all()
,它将给出一个包含所有响应的数组,从那里,您的问题将很容易得到解决
更多
,欢迎发表意见
我没有足够的声誉来评论返回由add()
创建的承诺,然后使用promise.all(taskContexts)
等待它们全部恢复resolve@Phil重复链接并没有真正的帮助,但是你的评论,除了firebase docs的链接之外,还有一个问题:不确定您是否还想结束这个问题。接受答案的第4点反映了我的评论,所以我不确定是什么问题,只是从这个答案中我不清楚。