【问题标题】:async function don't return value in right order异步函数不以正确的顺序返回值
【发布时间】:2021-04-12 12:40:06
【问题描述】:

我想从 firestore 获取用户数据,但函数的行为不符合我的要求。 当我运行 init 函数时,我在控制台中收到如下响应:" in init"、"after"、"null"、"user is active",但我想收到如下响应: "user is active", "in init", user data instead null," after";

我知道这可能很简单,但我整天坐在这个问题上。 我应该怎么做才能按此顺序获取数据?

init()

async function init () {
     await userIsActive()
    console.log("in init");     
  await getDaySpending();
    console.log("after") */
    
}

function userIsActive(){
    firebaseApp.auth().onAuthStateChanged( user=>{
    if(user){
      console.log("user is active");
      return true
    }else{
      console.log("no user");
      return false
    }
  })
  }

 function getDaySpending(period = '7-2020') {
    const user = firebase.auth().currentUser;
     console.log(user)    //I got null instead user data
    if(!user) return;      
    const uid = user.uid;
    const snap  = await  firebase.firestore().collection(uid).doc(period).get();
    if(snap.exists) {
      return snap.data().spending;
    } else {
      // handle the case where there was no data
    }
  }

【问题讨论】:

  • 代码中没有“null”登录,你的意思是“no user”吗?
  • 我延迟了不小心登录。是的,我得到了 null

标签: javascript firebase asynchronous google-cloud-firestore


【解决方案1】:

问题在于 userIsActive 函数。您不能从封闭的函数中返回值。

// This function returns undefined
function asd() {
  (() => { return 1; })();
}

在这种情况下,假设您正确使用我不熟悉的 firebase api,您需要使用明确的承诺。

function userIsActive(){
  return new Promise((resolve, reject) => 
    firebaseApp.auth().onAuthStateChanged( user=>{
    if(user){
      console.log("user is active");
      return resolve(true)
    } else{
      console.log("no user");
      return resolve(false);
    }
 })
}

我怀疑这不是使用此 api 的正确方法,因此希望对此主题更了解的人可以加入。

【讨论】:

  • 不客气。请标记为已回答。
【解决方案2】:

init 函数是async 如果不存在await,则不会暂停执行,然后您的代码将以非阻塞方式执行。添加关键字await。

Mozilla 文档:

一个异步函数可以包含一个等待表达式,它会暂停 执行异步函数并等待传递的 Promise 解决,然后恢复异步函数的执行和 返回解析后的值。

【讨论】:

  • 我应该把 await 关键字放在哪里?你能纠正我的功能吗?
  • 您在哪里调用它。 await init()
  • 当我在 init() 之前添加 await 时,出现错误:Unexpected reserved word
  • 那是因为你不是在异步函数中调用它,而是在主文件中调用它。试试这个: (async function() { await init(); })();但是,看起来问题是另一个问题 :) 很高兴你让它工作了。
猜你喜欢
  • 2022-11-16
  • 1970-01-01
  • 1970-01-01
  • 2015-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-20
  • 1970-01-01
相关资源
最近更新 更多