使用 resolve(x) 传递的数据被接收为未定义

data passed with resolve(x) is received as undefined

我正在尝试传递从下面的函数 getDownloadURL() 中获得的 url,它位于代码底部附近。问题这一方面的一切似乎都在工作 - 除了 resolve 似乎无法正常工作:

// Return a promise to catch errors while loading image
  getMediaFormulas(options, square): Promise<any> {

    // Get Image from ionic-native's built in camera plugin
    return this.camera.getPicture(options)
      .then((fileUri) => {

        // op Image, on android this returns something like, '/storage/emulated/0/Android/...'
        // Only giving an android example as ionic-native camera has built in cropping ability
        if (this.platform.is('ios')) {

          return this.crop.crop(fileUri, { quality: 2 });
        } else if (this.platform.is('android')) {
          // Modify fileUri format, may not always be necessary
          fileUri = 'file://' + fileUri;

          /* Using cordova-plugin-crop starts here */
          return this.crop.crop(fileUri, { quality: 2 });
        }
      })
      .then(newPath => {
        console.log(newPath);
        if(newPath) {
        let fileName = newPath.substring(newPath.lastIndexOf("/") + 1, newPath.length);
        let filePath = newPath.substring(0, newPath.lastIndexOf("/"));
        this.file.readAsDataURL(filePath, fileName).then(data =>{
          console.log("IN READASDATAURL GETMEDIAFORMULAS");
          //let strImage = data.replace(/^data:image\/[a-z]+;base64,/, "");
          //this.file.writeFile(this.file.tempDirectory, "image.jpg", strImage);
          //let blob = dataURItoBlob(data);

          //let file

          //this.getFileEntryRead(this.file.tempDirectory + '/image.jpg', square);
          var dataURL = data;

          let image       : string  = 'formula_' + this.username + '_' + new Date() + '.png',
            storageRef  : any,
            parseUpload : any,
            thisUrl: any;

          return new Promise((resolve, reject) => {
            storageRef       = firebase.storage().ref('/formulas/' + this.username + '/' + image);
            parseUpload      = storageRef.putString(dataURL, 'data_url');

            parseUpload.on('state_changed', (_snapshot) => {
                // We could log the progress here IF necessary
                console.log('snapshot progess ' + _snapshot);
              },
              (_err) => {
                 reject(_err);
                 console.log(_err.messsage);
              },
              (success) => {
                storageRef.getDownloadURL().then(url => {
                  console.log(url);
                  thisUrl = url;
                  console.log("IN READASDATAURL GETMEDIAFORMULAS UERLRLRLR");

                });

                resolve(thisUrl); 
              })
            }).catch(function(error) {
              console.log(error.message);
            });


        })
        }


      });


  }

我说 resolve 可能不起作用,因为在调用 getMediaFormula 的那一边,then 函数没有返回任何内容 - url 未定义.它在 actionsheet:

的选择之一中返回
presentActionSheet3() {
    let actionSheet = this.actionSheetCtrl.create({
      title: 'Choose source',
      buttons: [
        {
          text: 'Camera',
          handler: () => {
            let itemArrayTwo = this.profComponents.toArray();
            this.cameraService.getMediaFormulas(this.optionsGetCamera, this.square).then((url) => {
              actionSheet.dismiss();
              this.navCtrl.push(FormulapostPage, { path: url });
            }); //pass in square choice
            //this.myrenderer.setElementAttribute(this.itemArrayTwo[this.square - 1].nativeElement, 'src', 'block');
            console.log('camera clicked');
            //actionSheet.dismiss();
          }
        },{
          text: 'Photo Library',
          handler: () => {
            let itemArrayTwo = this.profComponents.toArray();

            this.cameraService.getMediaFormulas(this.optionsGetMedia, this.square).then((url) => {
              setTimeout(() => {
                console.log(url + " url url url url")
                actionSheet.dismiss();
                this.navCtrl.push(FormulapostPage, { path: url });
              },3000);

            }); //pass in square choice
            //this.myrenderer.setElementAttribute(this.itemArrayTwo[this.square - 1].nativeElement, 'src', 'block');
            console.log('camera clicked');
            //actionSheet.dismiss();
          }
        },{
          text: 'Cancel',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }

所以问题是对 getMediaFormulas 的调用的 then 正在返回并且未定义 url,但是在检索的代码中,在承诺中,它是正确创建的并像这样 resolve(thisUrl)resolve 中使用。为什么在操作表中未定义 url

这段代码有两个问题:

正如我在评论中指出的那样,您需要 return readAsDataUrl 承诺,例如:

...
let fileName = newPath.substring(newPath.lastIndexOf("/") + 1, newPath.length);
let filePath = newPath.substring(0, newPath.lastIndexOf("/"));
return this.file.readAsDataURL(filePath, fileName).then(data =>{
      console.log("IN READASDATAURL GETMEDIAFORMULAS");
      ...

此外,正如@trincot 所指出的,解析在错误的范围内,应该高一级,例如:

...
(success) => {
    storageRef.getDownloadURL().then(url => {
    console.log(url);
    thisUrl = url;
    console.log("IN READASDATAURL GETMEDIAFORMULAS UERLRLRLR");

    // Should be here, not outside of this then. Though as you mentioned it my have only been outside due to your testing
    resolve(thisUrl);
});
...