gpt4 book ai didi

javascript - 为什么这个数组变空了?

转载 作者:行者123 更新时间:2023-12-02 23:53:56 24 4
gpt4 key购买 nike

我正在我的 Firebase 应用程序中获取 Firebase 的一些数据。

我三次检查并调试了代码。第一次获取返回数组中的 5 个项目。然后我需要获取用户的 id 并进行另一次提取以从用户那里获取数据。这是我的代码:

export const fetchStyleItems = () => async dispatch => {
dispatch({ type: GET_STYLE_ITEMS_REQUEST });
database
.ref("styles_items")
.orderByChild("posted")
.once("value")
.then(function(snapshot) {
const exists = snapshot.val() !== null;
if (exists) data = snapshot.val();
var photo_feed = [];
for (var photo in data) {
const photoObj = data[photo];
database
.ref("users")
.child(photoObj.author)
.once("value")
.then(function(snapshot) {
const exists = snapshot.val() !== null;
if (exists) data = snapshot.val();
console.log(`inside the lasso ${photoObj} `);
photo_feed.push({
id: photo,
url: photoObj.url,
caption: photoObj.caption,
name: photoObj.name,
price: photoObj.price,
style_recomendation: photoObj.style_recomendation,
style_type: photoObj.style_type,
posted: photoObj.posted,
author: data.username
});

});
})
.catch(error => console.log(error));
}
console.log();
dispatch({
type: GET_STYLE_ITEMS_SUCCESS,
payload: photo_feed
});
})
.catch(error => console.log(error));
};

问题。当我调试代码并尝试分派(dispatch) GET_STYLE_ITEMS_SUCCESS 时,数组 photo_feed 变空。

我认为我在这里缺少一些范围。但我现在被困了 3 个小时,看不出出了什么问题。

最佳答案

我认为您正在 for in 循环中迭代数组并进行异步调用,但您并没有等待这些异步调用。因此,当您要分派(dispatch)数组时,photo_feed 为空

具体来说,在这里

for (var photo in data) {
const photoObj = data[photo];
database
.ref("users")
.child(photoObj.author)
.once("value")
.then(function(snapshot) {
// this is async
})

所以你应该等待这些 promise 。此外,您的函数是异步的,但您使用的是可链接的 .then() 方法,而不是等待(这就是添加异步的目的)。所以我重写了一点,并将您的 var 替换为 let

export const fetchStyleItems = () => async dispatch => {
try {
dispatch({ type: GET_STYLE_ITEMS_REQUEST });
let snapshot = await database
.ref("styles_items")
.orderByChild("posted")
.once("value");
const exists = snapshot.val() !== null;
if (exists) {
data = snapshot.val();
}
let photo_feed = [];
for (let photo in data) {
const photoObj = data[photo];
let snapshot = await database
.ref("users")
.child(photoObj.author)
.once("value");
const exists = snapshot.val() !== null;
if (exists) {
data = snapshot.val()
};
photo_feed.push({
id: photo,
url: photoObj.url,
caption: photoObj.caption,
name: photoObj.name,
price: photoObj.price,
style_recomendation: photoObj.style_recomendation,
style_type: photoObj.style_type,
posted: photoObj.posted,
author: data.username
});
}
dispatch({
type: GET_STYLE_ITEMS_SUCCESS,
payload: photo_feed
});
}
catch (e) {
console.log(e);
}
};

进一步阅读asyncawait

我不是100%确定await可以与for..in一起正常工作(我相信它可以);但是,如果没有,您可以将其替换为 for..of 循环并使用 Object.keys(data)

关于javascript - 为什么这个数组变空了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55500509/

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