[英]How to send Javascript/jQuery AJAX POST requests sequentially, looping over an array of request data, using Promises?
[英]switching from Jquery post requests to modern Promises
我正在一個Web應用程序項目中,后端使用Flask + Python,前端使用Javascript。 我想利用一些更現代的(ES6 / 7)風格的東西,例如Promises。
我目前一直在使用Jquery 3+編寫所有JavaScript。 大多數時候,我一次向服務器發出單個Ajax請求。 我一直在專門使用$.post
和.done()
和.fail()
編寫我的Ajax請求,我知道它們已經基於諾言或類似諾言。 我的大部分代碼都采用
我似乎總是要考慮服務器故障的情況+服務器成功的情況,但是它返回了錯誤的信息,我通常使用status
參數來控制它。 我一直在研究直接的Promise
語法, then, catch, resolve, reject
和我有一些問題。
考慮到我的簡單Ajax請求,從目前的格式切換到這種格式是否對我有好處?
它可以用來簡化當前編寫請求和處理失敗案例的方式嗎?
這是一個簡單的登錄示例,具有單擊登錄按鈕時調用的功能。
$('#loginsubmit').on('click', this, this.login);
// Login function
login() {
const form = $('#loginform').serialize();
$.post(Flask.url_for('index_page.login'), form, 'json')
.done((data)=>{
if (data.result.status < 0) {
// bad submit
this.resetLogin();
} else {
// good submit
if (data.result.message !== ''){
const stat = (data.result.status === 0) ? 'danger' : 'success';
const htmlstr = `<div class='alert alert-${stat}' role='alert'><h4>${data.result.message}</h4></div>`;
$('#loginmessage').html(htmlstr);
}
if (data.result.status === 1){
location.reload(true);
}
}
})
.fail((data)=>{ alert('Bad login attempt'); });
}
還有一個典型的更復雜的例子。 在這種情況下,當打開和關閉按鈕時,一些交互元素將被初始化。
this.togglediv.on('change', this, this.initDynamic);
// Initialize the Dynamic Interaction upon toggle - makes loading an AJAX request
initDynamic(event) {
let _this = event.data;
if (!_this.togglediv.prop('checked')){
// Turning Off
_this.toggleOff();
} else {
// Turning On
_this.toggleOn();
// check for empty divs
let specempty = _this.graphdiv.is(':empty');
let imageempty = _this.imagediv.is(':empty');
let mapempty = _this.mapdiv.is(':empty');
// send the request if the dynamic divs are empty
if (imageempty) {
// make the form
let keys = ['plateifu', 'toggleon'];
let form = m.utils.buildForm(keys, _this.plateifu, _this.toggleon);
_this.toggleload.show();
$.post(Flask.url_for('galaxy_page.initdynamic'), form, 'json')
.done(function(data) {
let image = data.result.image;
let spaxel = data.result.spectra;
let spectitle = data.result.specmsg;
let maps = data.result.maps;
let mapmsg = data.result.mapmsg;
// Load the Image
_this.initOpenLayers(image);
_this.toggleload.hide();
// Try to load the spaxel
if (data.result.specstatus !== -1) {
_this.loadSpaxel(spaxel, spectitle);
} else {
_this.updateSpecMsg(`Error: ${spectitle}`, data.result.specstatus);
}
// Try to load the Maps
if (data.result.mapstatus !== -1) {
_this.initHeatmap(maps);
} else {
_this.updateMapMsg(`Error: ${mapmsg}`, data.result.mapstatus);
}
})
.fail(function(data) {
_this.updateSpecMsg(`Error: ${data.result.specmsg}`, data.result.specstatus);
_this.updateMapMsg(`Error: ${data.result.mapmsg}`, data.result.mapstatus);
_this.toggleload.hide();
});
}
}
}
我知道這已經大致使用了Promise then catch
,但是我可以通過切換到Promise then catch
語法來改進代碼流嗎? 如您所見,我最終針對真實的失敗和成功的失敗重復了很多失敗案例代碼。 我的大多數代碼看起來都像這樣,但是嘗試將它們轉換為類似的內容時遇到了一些麻煩
promise_ajax_call
.then(do real success)
.catch(all failure cases)
我總是使用Bluebird Promises。 它們具有Promise.resolve函數,可以與ajax一起使用。 關於Promise的一件事,如果您在then
throw
一個錯誤,它將被束縛catch
。 一種清理方式可能是這樣的(請記住,這是偽的)
Promise.resolve($.ajax(...some properties..))
.then((data)=>{
if(data.result.status < 0){
//throw some error
}
// process the data how you need it
})
.catch((error){
// either the ajax failed, or you threw an error in your then. either way, it will end up in this catch
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.