【问题标题】:Why i can't pass variables with my function? [duplicate]为什么我不能用我的函数传递变量? [复制]
【发布时间】:2021-11-15 19:24:22
【问题描述】:

我在使用 firebase 的 react 本机应用程序中有此代码:

let bestTutors = [];

const getBestTutors = async () => {
    const snapshot = await getDoc(docRef);
    bestTutors = snapshot.data().list;
}

getBestTutors();

console.log(bestTutors);

但是当我运行它时,它只显示控制台日志“Array[]”,我尝试使用 .then() 和所有其他对我来说没有意义的东西,如果有需要使用它的话,idk没有等待或我如何将数据传递给变量:(?

【问题讨论】:

  • 你需要等待 getBestTutors()
  • 尝试使用 var 而不是 let。我认为问题出在区域上。
  • @tokkerbaz 不,这没有任何意义。

标签: javascript asynchronous


【解决方案1】:

看看我的cmets

您的代码 1

let bestTutors = [];

const getBestTutors = async () => {
    const snapshot = await getDoc(docRef);
    bestTutors = snapshot.data().list;
}

getBestTutors(); // Asynchronous function

console.log(bestTutors); // this is called before getBestTutors() returns the data. So console.log(bestTutors) return de default value: []

新代码

let bestTutors = [];

const getBestTutors = async () => {
    const snapshot = await getDoc(docRef);
    bestTutors = snapshot.data().list;
}

await getBestTutors(); // Wait until getBestTutors() has finished and then Next.

console.log(bestTutors);

【讨论】:

  • 我认为他应该修复它,但我给了我这个错误:“意外的标识符'getBestTutors'
  • 这里是我使用它的完整代码:codeshare.io/Wdk9WW
【解决方案2】:

使用等待调用函数。喜欢这个

await getBestTutors()

【讨论】:

  • 提供带格式的代码示例更便于他人参考。
猜你喜欢
  • 1970-01-01
  • 2011-03-29
  • 2013-10-02
  • 1970-01-01
  • 1970-01-01
  • 2019-03-04
  • 1970-01-01
  • 2012-01-15
相关资源
最近更新 更多