-1
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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Johnny
  • 31
  • 1
  • 4
  • You need to bind `this`. `storageRef.getDownloadURL().then(onResolve, onReject.bind(this));` – Oram Jan 13 '19 at 11:26
  • [bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) – Oram Jan 13 '19 at 11:27
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – jonrsharpe Jan 13 '19 at 11:36

1 Answers1

0

My gut instinct says that it's down to the this-reference. Try the code without a this, and/or use arrow functions to preserve its binding. E.g. (with inlined methods)

storageRef.getDownloadURL().then(() => {
  storageRef.getDownloadURL().then(function(url) {
    console.log(url);
    sMedia.playAudio(url);
    })
  console.log("File found!");
}).catch((e) => {
  this.presentAlert();  /* <---- >this< is the problem */
  console.log("File don't exist.")
});


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

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/this

Andreas Müller
  • 121
  • 1
  • 5