异步变量在条件逻辑中显示为空,但它存在于控制台日志中



我有点困惑于如何纠正这个异步问题。我有数据vocab,我知道我正在根据数据库中的数据成功填充。然而,目前我还不太清楚如何在稍后的函数中正确访问异步数据。想法?

export const fsFetchLessonVocab = async (
language: string,
id: string,
includeTranslations?: boolean,
translationLanguage?: string
) => {
const lesson = await fsFetchLesson(language, id).then((res) => res);
const lessonContent = await lesson.contentID.get();
const vocab = [];
try {
await lessonContent.data().words.forEach((word) => {
word.get().then((res) => {
vocab.push({ ...res.data(), id: res.id });
});
});
return vocab;
} catch (error) {
console.log('Error retrieving content', error);
}
if (includeTranslations) {
console.log('inbound vocab', vocab); //  YES - vocab array has content
if (vocab.length) {
//  NO - vocab is an empty array.
const translations = await vocab.forEach((word) => {
console.log('word', word);
});
console.log('translations', translations);
}
}
}

更多详细信息

const vocab = [];
try {
await lessonContent.data().words.forEach((word) => {
word.get().then((res) => {
vocab.push({ ...res.data(), id: res.id });
});
});
return vocab;
} catch (error) {
console.log('Error retrieving content', error);
}

^此块正在按预期工作。我的内容文档已经到达,我遍历单词的响应数组,找到每个引用并将其推送到vocab中。

if (includeTranslations) {
console.log('inbound vocab', vocab); // Populated array
if (vocab.length) {
// Empty array
const translations = await vocab.forEach((word) => {
console.log('word', word);
});
console.log('translations', translations);
}
}

^阵列vocab看起来填充在console.log()中,但是它在if()块内看起来是空的。


续:

我发现,当vocab显示和数组包含内容时,vocab.length在日志中显示0

试试这个代码:

try {
await Promise.all(
lessonContent.data().words.map(async word => {
const res = await word.get();
vocab.push({ ...res.data(), id: res.id });
}),
);
return vocab;
} catch (error) {
console.log('Error retrieving content', error);
}

如果res.data()也是异步的,那么您也需要等待

最新更新