我正在为一个项目使用 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/