2015-11-11 78 views
0

我使用cordova-plugin-file-transfer插件cordova与基于骨干的应用程序。如何使从cordova-plugin-file-transfer上传功能返回一个承诺

我有一个Backbone.View,它有一个名为saveReport的方法。然后我有一个Backbone.Model,它有一个叫savePic的功能。这是怎么myView.saveReport样子:

saveReport:function(){ 
    var promise = $.Deferred(); 
    promise.resolve(); 
    var that = this; 
    promise.then(function(){ 
     var savePicPromise = $.Deferred(); 
     savePicPromise.resolve(); 
     for(var i=1; i< that.miniatureViews.length; ++i){ 
     savePicPromise = savePicPromise.then(function(){ 
      return that.miniatureViews[i].pictureModel.savePic(); 
     }); 
     } 
     return savePicPromise; 
    }).then(function(){ 
     // here I do all other things 
     // ... 
     // ... 
    }); // promise chain. 

myModel.savePic看起来是这样的:

savePic: function(){ 
     var url = this.urlRoot; 
     var options = new FileUploadOptions(); 
     options.fileKey="image"; 
     options.fileName=this.imgURI.substr(this.imgURI.lastIndexOf('/')+1); 
     options.mimeType="image/jpeg"; 

     var ft = new FileTransfer(); 
     var myResponse; // to be set by callbacks. 

     var that = this; 
     this.savePromise = $.Deferred; // this should put a promise object into the model itself. 

     ft.upload(this.imgURI, 
     encodeURI(url), 
     function(r){ 
      that.savedURL = r.response; // this is the URL that the APi responds to us. 
      that.savePromise.resolve(); 
     }, 
     function(e){ 
      console.error(e); 
      window.analytics.trackEvent('ERROR', 'savingPic',e.code); 
      that.savePromise.fail(); 
     }, 
     options); 

     return this.savePromise; 
    }, 

我还做了在代码中的一些变化,也试图与其他2模型的方法,这种配置:

ft.upload(this.imgURI, 
     encodeURI(url), 
     this.resolveSavePromise, 
     this.failedSavePromise, 
     options); 

2功能:

resolveSavePromise: function(r){ 
     this.savedURL = r.response; // this is the URL that the APi responds to us. 
     this.savePromise.resolve(); 
    }, 
    failedSavePromise: function(e){ 
     console.error(e); 
     window.analytics.trackEvent('ERROR', 'savingPic',e.code); 
     this.savePromise.fail(); 
    }, 

注意:在第二个选项中,我不会在savePic方法中返回任何内容。

问题是,在saveReport方法的for循环中,存储在pictureModel中的promise实际上并不是承诺,或者至少表现得很奇怪。我得到一个错误信息this.savePromise.resolve()that.savePromise.resolve is not a function. (In 'that.savePromise.resolve()', 'that.savePromise.resolve' is undefined)"

有没有更好的方式使插件的upload函数很好地与promise一起工作?

感谢

回答

1

你忘了创建的推迟。你只是在做

this.savePromise = $.Deferred; 

,而你其实想

this.savePromise = new $.Deferred; // or 
this.savePromise = new $.Deferred(); // or 
this.savePromise = $.Deferred(); 

$.Deferred工厂确实没有.resolve方法。

顺便说一句,你会想要return this.savePromise.promise()而不是延期的对象。