Impossible to call any funciont inside function/promise

Promises are so strange for me.

Look at this code

playAudio(index){

   storageRef.getDownloadURL().then(onResolve, onReject);

   function onResolve() {
     storageRef.getDownloadURL().then(function(url) {
       console.log(url);
       sMedia.playAudio(url);
     })
     console.log("File found!")
   }

   function onReject() {
     this.presentAlert();  /* <---- This is the problem */
     console.log("File don't exist.")
   }

presentAlert() {
   let alert = this.alertCtrl.create({
     title: 'Ops!',
     subTitle: "No file for this search",
     buttons: ['OK']
   });
   alert.present();
}

This code seems to work. If the file exist on Firebase then the function onResolve() works fine. Instead if the file don’t exist then the console log is displayed but the function is not execute.

This because the function presentAlert() is invisible inside function onReject(). Why? How can i solve this problem?

Thank you!

Hello,

you are literally right. This is the problem.
You call this inside your function, but this this not this what you expect. This has changed his scope, so it point to something different you think.
So you can outside declare let that = this and use that instead or as @rapropos always says. Never use function inside use far arrow.

Best regrads, anna-liebt

1 Like