我正在获取用户数据,并且每个用户多次调用map函数.我想等到所有数据都被推送到数组,然后再处理数据.我尝试使用Promise.all(),但是没有用.
在继续之前,我如何等待地图功能完成?
不用说,在Promise.all()中打印时,数组user_list_temp为空.
const phone_list_promise_1 = await arrWithKeys.map(async (users,i) => {
return firebase.database().ref(`/users/${users}`)
.on('value',snapshot => {
user_list_temp.push(snapshot.val());
console.log(snapshot.val());
})
}
);
Promise.all(phone_list_promise_1).then( () => console.log(user_list_temp) )
Promise.all(arrWithKeys.map(async (users,i) => {
const eventRef = db.ref(`users/${users}`);
await eventRef.on('value',snapshot => {
const value = snapshot.val();
console.log(value);
phone_user_list[0][users].name = value.name;
phone_user_list[0][users].photo = value.photo;
})
console.log(phone_user_list[0]);
user_list_temp.push(phone_user_list[0]);
}
));
console.log(user_list_temp); //empty array
}
最佳答案
如果我正确理解了您的问题,则可以考虑将代码修改为使用常规的for..of循环,每个用户都有一个嵌套的promise,可以解决该用户的快照/值何时可用的问题,如下所示:
原文链接:https://www.f2er.com/js/531132.htmlconst user_list_temp = [];
/*
Use regular for..of loop to iterate values
*/
for(const user of arrWithKeys) {
/*
Use await on a new promise object for this user that
resolves with snapshot value when value recieved for
user
*/
const user_list_item = await (new Promise((resolve) => {
firebase.database()
.ref(`/users/${users}`)
.on('value',snapshot => {
/*
When value recieved,resolve the promise for
this user with val()
*/
resolve(snapshot.val());
});
}));
/*
Add value for this user to the resulting user_list_item
*/
user_list_temp.push(user_list_item);
}
console.log(user_list_temp);