我想从 Firebase实时数据库和 Firebase存储读取数据。首先读取RTDB。这是因为Firebase存储中存储的文件名是RDTB中数据的键。我有以下代码:
let newReadRef = firebase.database().ref('someRef').limitToLast(3).once('value').then(snapshot => {
let promiseArray = [];
snapshot.forEach(e => {
promiseArray.push(new Promise((resolve, reject) => {
//Do all the things I need to do before trying to get data from my Firebase Storage
let filePathRef = firebase.storage().ref(e.val().key);
filePathRef.getDownloadURL().then(url => {
//Do something with the url
resolve('Promise resolved');
}).catch(e => {
console.log(e);
reject('Rejected');
});
}));
});
Promise.all(promiseArray).then(someFunction);
});
想法是:
someFunction
进行某些操作,这将改变创建的数据似乎我的代码有点嵌套。有没有更好的方法来实现上述目标?
答案 0 :(得分:2)
不,代码几乎可以得到,但是由于您做的最后一件事返回一个Promise,因此您无需创建Promise
snapshot.forEach(e => {
//Do all the things I need to do before trying to get data from my Firebase Storage
let filePathRef = firebase.storage().ref(e.val().key);
promiseArray.push(
filePathRef.getDownloadURL()
.then(url => {
//Do something with the url
return 'Promise resolved';
}).catch(e => {
console.log(e);
throw 'Rejected';
});
);
});
我本来建议使用.map
而不是.forEach
,但是如果我记得, snapshot
不是Javascript数组(它有一个forEach,但没有地图方法)