Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Firebase添加内部for循环_Javascript_Firebase_Google Cloud Firestore - Fatal编程技术网

Javascript Firebase添加内部for循环

Javascript 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

我正在地图中运行firebase
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点反映了我的评论,所以我不确定是什么问题,只是从这个答案中我不清楚。