【问题标题】:Typescript get object outside the function打字稿在函数外获取对象
【发布时间】:2018-03-18 01:24:45
【问题描述】:

我有一个用于创建新的 firebase 用户的打字稿功能。 我想在函数之外获取用户对象(由该函数创建),但是当我尝试 console.log 时,我在控制台中得到“未定义”。

async saveProfile(){

const secondaryApp = this.firebase.initializeApp(this.config,"appname2");
var X;

try {


  secondaryApp.auth().createUserWithEmailAndPassword(this.em, this.pwd)
  .then(function test(firebaseUser) {


    X = firebaseUser;

    //Here I CAN GET THE OBJECT X
    console.log(X);
    secondaryApp.auth().signOut();

  })
    //I WANT TO GET THE X OBJECT HERE !!
    //BUT I GET "UNDEFINED"
    console.log(X);
}

catch(e){
    console.error(e);
    this.toast.create({
      message: e.message,
      duration: 3000
    }).present();
  }     
}

对不起,如果这个问题有点愚蠢,但我是初学者,尤其是使用打字稿。谢谢:)

【问题讨论】:

    标签: typescript


    【解决方案1】:

    .then() 之外的代码在 Promise(由createUserWithEmailAndPassword 返回)完成之前运行。

    你必须等待它,这就是.then() 句柄中的console.log(X) 起作用的原因。

    解决办法:

    由于您在async 函数中,因此可以使用await

    async saveProfile() {
      const secondaryApp = this.firebase.initializeApp(this.config, "appname2");
      var X;
    
      try {
        // added await below
        X = await secondaryApp.auth().createUserWithEmailAndPassword(this.em, this.pwd);
        secondaryApp.auth().signOut(); 
        console.log(X);
      } catch (e) {
        console.error(e);
        this.toast.create({
          message: e.message,
          duration: 3000
        }).present();
      }
    }
    

    【讨论】:

    • 它现在可以工作了,感谢您的解释和快速解决方案。
    • 当然,很高兴它有帮助。也感谢您的接受。 JSYK 我认为你刚刚获得了足够的支持声望。恭喜!
    猜你喜欢
    • 2018-12-12
    • 2019-04-29
    • 2021-11-09
    • 2022-01-12
    • 1970-01-01
    • 2018-07-03
    • 2018-06-26
    • 2023-03-07
    • 2021-10-09
    相关资源
    最近更新 更多