我使用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一起工作?
感謝