Из вашего кода видно, что вы используете ES6 (вы используете функции стрелок).Вы можете следовать рекурсивному подходу с функциями и обещаниями стрелки es6, это может быть что-то вроде этого:
doAjaxRequest(data) {
fireAPICall(data).then(response => { // fireAPICall is a method that fires the post request and returns the response received from server
if(response.status == 200) { // success (this if statement is optional)
// handle success
let d = response.data;
}
}).catch(error => { // failure
data.iTries++;
if(data.iTries < 40) {
window.setTimeout(() => {doAjaxRequest(data)}, 9000); // try again
} else if(data.iTries < 20) {
window.setTimeout(() => {doAjaxRequest(data)}, 30000); // try again
}
});
}
Для метода fireAPICall
вы можете использовать любой основанный на обещаниях http-клиент, такой как axios или Fetch API , здесь я использую axios
:
fireAPICall(data) {
return axios.post("url", data);
}
Обновление : если вы хотите обрабатывать как reject/failure
событие, так и notify/progress
событий, для этого потребуется совместная работа на стороне сервера.Вы можете заставить свой сервер возвращать код состояния 202
(или любой другой более подходящий код состояния) в случае события прогресса (пока не готово), и вы можете обработать это в обратном вызове .then()
:
doAjaxRequest(data) {
fireAPICall(data).then(response => { // fireAPICall is a method that fires the post request and returns the response received from server
if(response.status === 202) { // notify/progress event
data.iTries++;
if(data.iTries < 40) {
window.setTimeout(() => {doAjaxRequest(data)}, 9000); // try again
} else if(data.iTries < 20) {
window.setTimeout(() => {doAjaxRequest(data)}, 30000); // try again
} else {
return Promise.reject('poll eneded with no success'); // exceeded maximum number of times for polling, so reject. This will invoke the catch callback method with this error
}
} else { // handle success
let d = response.data;
}
}).catch(error => { // reject/failure for some other reason
// handle error
});
}