我正在获取我的用户数据, map 函数为每个用户调用了多次。我想等到所有数据都被推送到数组中,然后再操作数据。我尝试使用 Promise.all() 但它没有用。 在继续之前如何等待此 map 功能完成?
不用说,数组 user_list_temp
在 Promise.all() 中打印时是空的。
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
}
最佳答案
可以将 async/await
与 firebase 一起使用
这就是我通常制作 Promise.all
const db = firebase.database();
let user_list_temp = await Promise.all(arrWithKeys.map(async (users,i) => {
const eventRef = db.ref(`users/${users}`);
const snapshot = await eventref.once('value');
const value = snapshot.value();
return value;
})
);
这篇文章很好地解释了如何使用 Promise.all
和 async/await
https://www.taniarascia.com/promise-all-with-async-await/
以下是我将如何重构您的新代码片段,这样您就不会混合使用 promises
和 async/await
let user_list_temp = await Promise.all(arrWithKeys.map(async (users,i) => {
const eventRef = db.ref(`users/${users}`);
const snapshot= await eventRef.once('value');
const value = snapshot.val();
console.log(value);
phone_user_list[0][users].name = value.name; // should this be hardcoded as 0?
phone_user_list[0][users].photo = value.photo; // should this be hardcoded as 0?
console.log(phone_user_list[0]);
return phone_user_list[0]; // should this be hardcoded as 0?
})
);
console.log(user_list_temp);
这是一个使用 fetch 而不是 firebase 的简单示例:
async componentDidMount () {
let urls = [
'https://jsonplaceholder.typicode.com/todos/1',
'https://jsonplaceholder.typicode.com/todos/2',
'https://jsonplaceholder.typicode.com/todos/3',
'https://jsonplaceholder.typicode.com/todos/4'
];
let results = await Promise.all(urls.map(async url => {
const response = await fetch(url);
const json = await response.json();
return json;
}));
alert(JSON.stringify(results))
}
关于javascript - 等待所有 firebase 调用完成 map 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54524461/