Issue
I am trying to convert this ionic 3 code into ionic 4 but I don't know how the promise works on ionic 4. I tried looking into the documentations and I can't find any solutions to promises
async generateAlert(header, message, ok, notOk): Promise<boolean> {
return new Promise((resolve, reject) => {
let alert = await this.alertController.create({
header: header,
message: message,
buttons: [
{
text: notOk,
handler: _=> reject(false)
},
{
text: ok,
handler: _=> resolve(true)
}
]
})
await alert.present();
});
}
Solution
As you can see here:
The await operator is used to wait for a Promise.
So await
is just another way to work with promises like you can see in the following example:
// Method that returns a promise
private resolveAfter2Seconds(x: number): Promise<number> {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
// Using await
private async f1(): Promise<void> {
var x = await resolveAfter2Seconds(10);
console.log(x); // 10
}
// Not using await
private f2(): void {
resolveAfter2Seconds(10).then(x => {
console.log(x); // 10
});
}
In f1(){...}
you can see how the app will wait for the promise to be resolved before executing the next line of code. That's why you can do something like
var x = await resolveAfter2Seconds(10);
console.log(x); // 10
without putting that console.log(x)
in a .then(() => {...})
block.
In f2()
since we don't use await
, the app won't wait for the promise to be resolved before executing the next line of code, so we must use then
to print the result in the console:
resolveAfter2Seconds(10).then(x => {
console.log(x); // 10
});
That being said, if you just want to create a method that shows an alert and returns true/false when the user selects the ok
/notOk
buttons, you can do the following (which doesn't use await
at all):
private generateAlert(header: string, message: string, ok: string, notOk: string): Promise<boolean> {
return new Promise((resolve) => {
// alertController.create(...) returns a promise!
this.alertController
.create({
header: header,
message: message,
buttons: [
{
text: notOk,
handler: () => resolve(false);
},
{
text: ok,
handler: () => resolve(true);
}
]
})
.then(alert => {
// Now we just need to present the alert
alert.present();
});
});
}
Then you can use that method like this
private doSomething(): void {
// ...
this.generateAlert('Hello', 'Lorem ipsum', 'Ok', 'Cancel').then(selectedOk => {
console.log(selectedOk);
});
}
Answered By - sebaferreras
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.