我使用promises进行多次ajax调用如何通过设置标志返回上一个函数。我有一个保存函数,我在其中调用方法if(!x()){return;}
我想从x函数中返回一些标志我使用promises进行ajax调用,因为我需要等待多个ajax请求响应并依赖于它我必须提交表格。请检查小提琴Fiddle
答案 0 :(得分:0)
除非你熟悉Promises,否则这种事情是一场噩梦。
据我所知,你想要这样的东西:
Ext.define('MyApp.view.MyModel1FormViewController', {
'extend': 'Ext.app.ViewController',
'alias': 'controller.mymodel1form',
'save': function (button, e, eOpts, processed) {
var me = this;
// enable/disable "submit" button based on Promise-wrapped result from refValid()
return this.refValid().then(function(bool) {
// success handler
me.onSubmit(button, e, eOpts, bool);
Ext.Msg.alert('save: success');
}, function (e) {
// error handler
// me.onSubmit(button, e, eOpts, ???); true|false or maybe just leave the button in its current state?
Ext.Msg.alert('save: errors');
// throw e; // rethrow the error to inform save()'s caller.
});
},
'refValid': function (button, e, eOpts) {
var detailStore = this.getView().up('panel').lookupReference('list').getStore(),
jde = this.getView().up('panel').lookupReference('headerform').lookupReference('jdeno').getValue();
var promises = detailStore.data.items.map(function (r) { // ???
return r.get('refno') || null;
}).filter(function (x) {
return !!x; // filter out any nulls
}).map(function (customerInvoiceDebitNo) {
return Ext.Ajax.request({
'url': 'data1.json',
'timeout': 120000,
'method': 'GET',
'params': {
'addressNumber': jde,
'documentNumber': customerInvoiceDebitNo
},
'customerInvoiceDebitNo': customerInvoiceDebitNo
}).then(function (response) {
if (Ext.decode(response.responseText).data.length === 0) {
return false; // null
} else {
Ext.Array.remove(customerInvoiceDebitNo); // maybe not necessary?
return true; // not null
}
});
});
return Ext.Promise.all(promises).then(function (results) { // results is array of booleans
// Scan the results to check whether or not all are `true`,
// and return <boolean>.
return results.reduce(function (prev, current) {
return prev && current;
}, true);
});
}
});