I have a for
loop, and in one iteration (of something) I need to make four AJAX requests, then wait until result from the last request.
- jQuery Deferred - getting result of chained ajax calls
- chaining jquery .when().then() in a loop with fixed end of chain call
- How to make for loop wait until Async call was successful before to continue
Now I've got only how to pass data from previous promise to another, like in this cool answer, but I need to return the value from the last AJAX call to the outer array (and wait until the last AJAX call is done) and then continue other functions out of the loop.
attaches.forEach(function(attach)) {
if(attach.val == "val1"){
attachments.push(attach.val1);
}
if(attach.val == "val2"){
attachments.push(attach.val2);
}
if(attach.val == val3){
function func1(){
var params = [param1,param2];
return $.post(api, params.join('&'))
}
function func2(){
console.log('1111');
return new Promise(function(resolve, reject)) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
}
xhr.open('GET', img_src);
xhr.responseType = 'blob';
xhr.send();
});
}
function uploadPhoto(upload_url, bulbSend){
console.log('<Del><F7> function uploadPhoto');
return $.ajax({
url: upload_url,
type: 'POST',
data: bulbSend,
dataType: 'json',
processData: false,
contentType: false,
});
}
function saveResult(params){
return $.post(api, params.join('&'))
}
func1().then(fun1hand()).then(console.log('a32w436bya3b7naua'));
function fun1hand(){
return function(dat4a) {
return func2().then(func2hand(dat4a));
};
}
function func2hand(dat4a){
console.log('2222');
return function(datums){
console.log('3333');
var upload_url = dat4a.upload_url;
console.log('UPLOAD__URL BEFORE PROMISE '+upload_url);
var bulbSend = new FormData();
bulbSend.append('file1', datums, 'file.jpg');
return uploadPhoto(upload_url,bulbSend).then(func3hand());
}
}
function func3hand(){
return function(data2){
var params = [data2.param1, data2.param2, data2.param3];
return saveResult(params).then(pushToAttachmentsHandler());
}
}
function pushToAttachmentsHandler(){
return function(data3){
console.log('PUSUSUSUSSUSUSUUSUS PUSHHHHHHH PUSH DA BAUTTON');
console.log(attachments);
return pushDat(data3).then(console.log(attachments));
}
}
function pushDat(data3){
console.log('1111');
return new Promise(function(resolve, reject) {
attachments.push(data3.param3+"_"+data3.param1));
console.log('11111111111');
});
}
}
});
Functions that are out of loop start their console.log
s before console.log('3333')
inside promises... but they need await until AJAX calls inside the loop are done and loop is completed.
And now I need to repeat AJAX after timeout if it was rejected (server requests limit per second) - how could I set it in my code for native XMLHttpRequest()
that is inside of promise, and for jQuery AJAX calls that are returned?