2015-11-11 75 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()而不是延期的對象。