等到异步调用完成 - Ionic2

时间:2016-09-14 18:55:01

标签: javascript angular typescript ionic2

我在Ionic2工作,我遇到了这个问题: 在我的组件中,有drawPlayer方法从firebase数据库中检索数据。

这是它的代码:

drawPlayer(){
    this.playerData.drawThePlayer().on('value', snapshot => {
      // some stuff
    });
    return this.drawnPlayer;   // returns the player name
}

ngOnInit函数内的同一文件(组件)中,我需要调用drawPlayer()并执行:

ngOnInit(){
let myVar = this.drawPlayer();
console.log("test: "+myVar);
}

如果我检查控制台,我会阅读test: undefined,如果我返回并再次返回该页面,我会看到test: a correct value。我认为这是因为drawPlayer()是异步调用,当我console.log时它还没有返回结果。

那么,console.log完成后我才能drawPlayer()怎么办?

/ ********************************************** ******************************* /

编辑:(在httpNick回答之后)

现在我有了这个带有完整代码的drawPlayer()方法(this.drawnPlayer是从这些方法中全局定义的):

drawPlayer(cb){
    this.playerData.drawThePlayer().on('value', snapshot => {
      var data = snapshot.val();
      for (var key in data){
            this.drawnPlayer = String(data[key].lastName);
            console.log("playerName: "+this.drawnPlayer);
      }
    });
    console.log("test: "+this.drawnPlayer);
    cb(this.drawnPlayer);   // returns the player name
}

ngOnInit()是这样的:

this.drawPlayer(function(valueFromDrawPlayer) {
    console.log("callback result: "+valueFromDrawPlayer);
});
console.log("after the callback");

当我运行应用程序时,这就是我在浏览器控制台中看到的内容:

test: undefined
callback result: undefined
after the callback
EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property '0' of undefined
playerName: John

但我希望读到这个:

playerName: John
test: John
callback result: John
after the callback

2 个答案:

答案 0 :(得分:0)

我不确定this.drawnPlayer来自哪里,但如果您将回调函数传递给drawPlayer,则可以在异步代码运行完毕后调用该函数以便能够记录返回值。

drawPlayer(cb){
    this.playerData.drawThePlayer().on('value', snapshot => {
      // some stuff
    });
    cb(this.drawnPlayer);   // returns the player name
}
ngOnInit(){
    drawPlayer((x) => { console.log(x) });
}

最后一行也可以改写为:

drawPlayer(function(valueFromDrawPlayer) {
    console.log(valueFromDrawPlayer);
});

查看完全代码后编辑:

drawPlayer(cb){
    this.playerData.drawThePlayer().on('value', snapshot => {
      var data = snapshot.val();
      for (var key in data){
            this.drawnPlayer = String(data[key].lastName);
            console.log("playerName: "+this.drawnPlayer);
            cb(this.drawnPlayer);   // returns the player name
      }
    });
}

答案 1 :(得分:-2)

尝试围绕异步调用创建同步包装器。通常你不想这样做,因为它会阻塞整个线程池。如果是必须使用等待阻止异步返回方法。它本质上违背了首先使用异步的目的。

   public static whatever CallAndWaitAsync()
   {
       task.Wait(); // Block thread until completed
       var result = task.Result;
       return result;
   }