I am developing in Ionic2 and encountering an issue:
Within my component, there is a method called drawPlayer
that fetches data from a Firebase database.
Here is the code for this method:
drawPlayer(){
this.playerData.drawThePlayer().on('value', snapshot => {
// some stuff
});
return this.drawnPlayer; // returns the player name
}
In the same file (component), within the ngOnInit
function, I call the drawPlayer()
method as follows:
ngOnInit(){
let myVar = this.drawPlayer();
console.log("test: "+myVar);
}
Upon inspecting the console, I notice that it prints test: undefined
. However, if I navigate back and then return to the page, I see test: a correct value
. This behavior leads me to believe that the drawPlayer()
call is asynchronous, causing the console log to execute before the result is returned.
Therefore, my question is how can I ensure that console.log
only runs after drawPlayer()
has completed its execution?
/*****************************************************************************/
EDIT: (following httpNick's response)
I have now updated the drawPlayer()
method with the complete code (note that this.drawnPlayer
is defined globally outside these methods):
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
}
The ngOnInit()
function now looks like this:
this.drawPlayer(function(valueFromDrawPlayer) {
console.log("callback result: "+valueFromDrawPlayer);
});
console.log("after the callback");
When running the app, the browser console displays:
test: undefined
callback result: undefined
after the callback
EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property '0' of undefined
playerName: John
However, my expected output should be:
playerName: John
test: John
callback result: John
after the callback