【问题标题】:Impossible to call any function inside function/promise不可能在函数/承诺中调用任何函数
【发布时间】:2019-06-07 15:56:28
【问题描述】:
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();
}

此代码似乎有效。如果文件存在于 Firebase 上,则 onResolve() 函数可以正常工作。相反,如果文件不存在,则会显示控制台日志,但不会执行该函数。

这是因为函数 presentAlert() 在函数 onReject() 中是不可见的。为什么? 我该如何解决这个问题?

【问题讨论】:

标签: typescript ionic3


【解决方案1】:

我的直觉说这取决于 this-reference。尝试不带 this 的代码,和/或使用箭头函数来保留其绑定。例如。 (使用内联方法)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-12
    • 2022-01-08
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2015-08-13
    相关资源
    最近更新 更多