javascript - 使用 firebase 调用时如何在 forEach 内使用异步调用

标签 javascript vue.js asynchronous vuejs2

我的问题是我无法弄清楚如何使用 Firestore 使此代码正常工作(不确定这是否无关紧要)。

实际代码如下:

prestamoItems() {
      var myarray = [];
      var myobject = {};

      //here comes the first async method (works OK)

      fb.prestamosCollection
        .orderBy("fechaPrestamo", "desc")
        .get()
        .then(val => {
          if (!val.empty) {

            //here comes forEach

            val.docs.forEach(doc => {
              myobject = doc.data();
              myobject.id = doc.id;
              console.log("The doc id is " +myobject.id)

              //here comes second async call inside the forEach loop, but it doesnt wait for this 
              //to be finished, and immediately goes to the other step

              fb.equiposCollection.doc(myobject.id).get().then(eqp => {
                console.log("The doc id from the other collection is " +eqp.id)
              })

              myarray.push(myobject)
              console.log("myobject pushed to myarray")
            });


          }
        });
    }

请注意,我在 forEach 循环内调用来自另一个异步方法的异步方法。在代码的每个变体中,我得到的输出(控制台日志)如下:

11:13:14.999 Prestamos.vue?18d2:71 The doc id is 1yTCUKwBvlopXX2suvVu
11:13:14.999 Prestamos.vue?18d2:78 myobject pushed to myarray
11:13:15.000 Prestamos.vue?18d2:71 The doc id is Z5TE15Fj3HFrn1zvceGe
11:13:15.000 Prestamos.vue?18d2:78 myobject pushed to myarray
11:13:15.000 Prestamos.vue?18d2:71 The doc id is JNN9aN65XE1tUTmlzkoJ
11:13:15.000 Prestamos.vue?18d2:78 myobject pushed to myarray
11:13:15.000 Prestamos.vue?18d2:71 The doc id is NF2hHCpM8leZezHbmnJx
11:13:15.001 Prestamos.vue?18d2:78 myobject pushed to myarray
11:13:15.364 Prestamos.vue?18d2:74 The doc id from the other collection is 1yTCUKwBvlopXX2suvVu
11:13:15.368 Prestamos.vue?18d2:74 The doc id from the other collection is Z5TE15Fj3HFrn1zvceGe
11:13:15.374 Prestamos.vue?18d2:74 The doc id from the other collection is JNN9aN65XE1tUTmlzkoJ
11:13:15.379 Prestamos.vue?18d2:74 The doc id from the other collection is NF2hHCpM8leZezHbmnJx

因此,forEach 循环不会等待其中的异步函数(据我所知,这实际上是预期的行为)。

问题是如何让它等待内部调用完成后再将对象添加到数组中?提前致谢。

最佳答案

要么将依赖于先前结果的代码嵌套到 then() 回调中,要么将循环(forEach 不支持异步)包装在 async< 中 block 在内部使用 await 。例如:

fb.prestamosCollection
  .orderBy("fechaPrestamo", "desc")
    .get()
    .then(val => {
      if (!val.empty) {
        // wrap loop in async function call iife so we can use await inside
        (async () => {
          for (var i = 0; i < val.docs.length; i++) {
            const doc = val.docs[i];
            myobject = doc.data();
            myobject.id = doc.id;
            // this will be synchronous now
            let eqp = await fb.equiposCollection.doc(myobject.id).get();
            console.log(eqp.id);
            myarray.push(myobject)
          }
        })();
      }
    });

关于javascript - 使用 firebase 调用时如何在 forEach 内使用异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58919068/

相关文章:

c# - Async WebRequest 卡住应用程序

javascript - 如何使用 Javascript API 在 OnlyOffice 文档编辑器中格式化表格单元格

javascript - 从 Vuex Store 中的 action 中推送路由

javascript - 类型 '' 上不存在属性 'Request<ParamsDictionary>'

javascript - 将数据传递给组件

multithreading - 在 segue 之前等待异步方法

javascript - React库如何重新渲染组件

css - 如何使用 JS 为计时器卡设置边框动画

git - 为现有存储库生成项目

javascript - Ember.js 异步模型