Hello,
I am new to promises. I am trying to compare my package name with a string. I am using the AppVersion plugin:
[https://ionicframework.com/docs/native/app-version/](App Version Doc)
I use the following code:
async getPackageInfo() {
this.package = await this.appVersion.getPackageName();
console.log("Package: " + this.package); //Prints "Package: com.my.package"
}
I call this.getPackageInfo() in the constructor.
In another method I call later I have
checkPackage() {
console.log(this.package); ///this prints undefined
if(EXPECTED_PACKAGE_NAME == this.package) {
return "AppName";
}
}
I have also tried calling getPackageInfo() in this method.
What am I doing wrong here?
How are you doing this, exactly?
Like this:
constructor(private appVersion: AppVersion) {
this.getPackageInfo();
}
OK, especially if you’re new to dealing with futures (like Promise
s), I think it would be best to pretend for a bit that async
and await
don’t exist. They look a lot simpler than they actually are, and obscure a lot of what is really going on.
Another good habit is to always declare a return type for every function you write. In this example, you need to think about what getPackageInfo
can return.
…time passes…
It has to be a Promise<string>
(pretty much just what you get from appVersion.getPackageName()
). Everywhere you call getPackageName
from (including that constructor) is going to have to deal with that Promise
and chain a then()
clause off of it to do something with what it resolves to.
The reason this didn’t work as written is because you would have to await
getPackageInfo(), which you can’t do in that constructor without making the constructor async
(a further impossibility).