gpt4 book ai didi

javascript - 循环数据以提取 Firebase 值数组

转载 作者:行者123 更新时间:2023-12-01 02:24:00 25 4
gpt4 key购买 nike

我有一个包含 N 个路径的数组,用于从 Firebase 数据库中的不同位置检索数据。

searchPaths = ['位置/日期1/imageID', '位置/日期2/imageID2', 位置/日期3/imageID3, ...]

现在,我想循环遍历每个搜索路径并从中提取一个值以保存图像 URL 数组。

    const searchPaths = ['locations/date1/imageID', 'locations/date2/imageID2']
const imageURLs = []

for(var Obj in searchPaths)
{
const path = Obj
admin.database().ref(path).once('value').then(snapshot =>
{
const URL = snapshot.val().fileURL;
imageURLs.push(URL);
console.log('ImageURL: ' + URL );
})
// here is where it gets sour
}.then(() => {
console.log("All image URL's" + imageURLs")
}

所以,我的问题是,当我们现在从每个引用中提取了所需的数据时,如何返回 promise ?是否有 Promise.all 类型?它去哪儿了?

最佳答案

您可以使用 for 循环创建一个 Promise 数组,然后使用 Promise.all,我知道很粗糙,但它应该可以工作。

const searchPaths = ['locations/date1/imageID', 'locations/date2/imageID2']
const imageURLs = []
var promises = [];
for(var Obj in searchPaths)
{
promises.push(new Promise(function(resolve, reject) {
const path = Obj
admin.database().ref(path).once('value').then(snapshot =>
{
const URL = snapshot.val().fileURL;
imageURLs.push(URL);
console.log('ImageURL: ' + URL );

//resolve the promise after pushing imageURL
resolve();
})
}));
}

//when all of them are done:
Promise.all(promises)
.then(function(results) {
//code when done...
})

关于javascript - 循环数据以提取 Firebase 值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48964499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com