javascript - .then 的链接不起作用

标签 javascript firebase asynchronous google-cloud-firestore es6-promise

我正在为一个项目使用 Firebase,但在链接 then() 时遇到问题。

我将有关用户的数据存储在一个对象中。 user 的一个属性是对另一组名为 events 的数据的引用数组。我循环遍历引用以读取 Firestore (Firebase DB) 中的数据并将其存储到名为“用户”的本地对象中。

打印用户对象时,首先显示第三个 then() 的输出语句。从逻辑上讲,每个 then 都应该在它上面的那个之后执行,但是第三个 then() 被异步执行并首先打印输出。这是什么原因?此外,任何 then() 都没有返回任何值。这是问题的根源吗?

orgRef.collection('collection').doc('doc').get()
  .then(function(data){
  user.info = data.data();
})
  .then(function(){
  user.info.events.forEach(function(event){
    eventRef.get()
      .then(function(data){
      user.eventdata[event] = data.data()[event];
    })
      .then(function(){
      console.log(user);
    });
  });
})
  .then(function(){
  console.log('AT END');
  console.log(user);
});

我添加了输出,每个 console.log 语句都打印相同的对象“用户”。该对象被打印了三次,因为循环执行了两次并打印了该对象。第三个是因为对主要 get() promise 的 then() 语句。

AT END
{ 
  eventdata: {} 
}
{ 
  eventdata:
   { FEENbYcy04k6XPR148rv:
       //more data
   } 
}
{ 
  eventdata:
   { FEENbYcy04k6XPR148rv:
       //more data
     622kUqbF9jftq1nKkQSb:
       //more data  
   } 
}

最佳答案

您需要正确地链接 promise 。照原样,你的 eventRef.get().then s 未连接到您的最终 'AT END'那么。

使用 Promise.all将一组 promise 变成一个,然后返回第三个 promise then .

orgRef.collection('collection').doc('doc').get()
  .then(function(data) {
    user.info = data.data();
  })
  .then(function() {
    const allPromises = user.info.events.map(function(event) {
      return eventRef.get()
        .then(function(data) {
          user.eventdata[event] = data.data()[event];
        })
        .then(function() {
          console.log(user);
        });
    });
    return Promise.all(allPromises);
  })
  .then(function() {
    console.log('AT END');
    console.log(user);
  });

你也可以通过使用 ES6 箭头函数和隐式返回使它更简洁:

orgRef.collection('collection').doc('doc').get()
  .then(data => user.info = data.data())
  .then(() => (
    Promise.all(user.info.events.map((event) => (
      eventRef.get()
        .then(data => user.eventdata[event] = data.data()[event])
        .then(() => console.log(user))
    )))
  ))
  .then(() => {
    console.log('AT END');
    console.log(user);
  });

关于javascript - .then 的链接不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49962857/

相关文章:

javascript - 通过 getContext 从 HTML 标记中获取文本 - Google Apps 脚本 - 电子表格

firebase - Firestore 安全规则 - 未找到函数

java - Spring 延迟结果丢失了 http session

php - 使用PHP(和Symfony)的无状态和异步Web服务器

javascript - React useState 导致渲染循环

javascript - 一次查询多个型号

firebase - 在哪里以及如何正确使用 Firebase 的 enablePersistence() 方法以离线使用网络应用程序?

javascript - 延迟返回等待异步函数(在卸载事件之前)

javascript - 使用脚本标签的跨站点脚本,更改脚本标签的 src,我们可以使用 id 作为脚本标签

swift - 我可以在两个单独的 View Controller 上获得相同的 firebase 数据吗?