/ / async के लिए वैकल्पिक: झूठी अजाक्स - जावास्क्रिप्ट, jquery, अजाक्स

async के विकल्प: झूठी AJAX - जावास्क्रिप्ट, jquery, AJAX

मैं एक सरणी के माध्यम से लूप करता हूं जो प्रत्येक के लिए एक अजाक्स अनुरोध चला रहा है। मुझे क्रम में होने वाले अनुरोधों की आवश्यकता है, इसलिए मैं अंतिम अनुरोध उठा सकता हूं और सफलता पर एक समारोह चला सकता हूं।

फिलहाल im चल रहा है (सरलीकृत):

$.each(array, function(i, item){
ajax_request(item.id, item.title, i);
})

function ajax_request(id, title, i){
$.ajax({
async: false,
url: "url here",
success: function(){
if(i == array.length-1){
// run function here as its the last item in array
}
}
})
}

हालाँकि, async का उपयोग कर:गलत एप्लिकेशन को गैर-जिम्मेदार / धीमा बनाता है। लेकिन, बिना async: गलत कभी-कभी अनुरोधों में से एक थोड़ा लटका होगा और वास्तव में अंतिम भेजे गए ajax अनुरोध रिटर्न के बाद वापस आ जाएगा।

कैसे मैं async का उपयोग कर के बिना इसे लागू कर सकते हैं: गलत?

उत्तर:

जवाब के लिए 5 № 1

आप ajax कॉल चलाने के लिए और प्रत्येक सफल सफलता हैंडलर में एक स्थानीय फ़ंक्शन का उपयोग कर सकते हैं, आप अगले ajax कॉल को किक कर सकते हैं।

function runAllAjax(array) {
// initialize index counter
var i = 0;

function next() {
var id = array[i].id;
var title = array[i].title;
$.ajax({
async: true,
url: "url here",
success: function(){
++i;
if(i >= array.length) {
// run function here as its the last item in array
} else {
// do the next ajax call
next();
}

}
});
}
// start the first one
next();
}

वादों का उपयोग करने वाले विकल्प के साथ 2016 में इस उत्तर को अपडेट करना। यहाँ आप श्रृंखला में अनुरोधों को कैसे चलाते हैं:

array.reduce(function(p, item) {
return p.then(function() {
// you can access item.id and item.title here
return $.ajax({url: "url here", ...}).then(function(result) {
// process individual ajax result here
});
});
}, Promise.resolve()).then(function() {
// all requests are done here
});

यहाँ है कि आप उन्हें कैसे समानांतर में चलाते हैं, सभी परिणाम लौटाते हैं:

var promises = [];
array.forEach(function(item) {
// you can access item.id and item.title here
promises.push($.ajax({url: "url here", ...});
});
Promise.all(promises).then(function(results) {
// all ajax calls done here, results is an array of responses
});

उत्तर № 2 के लिए 1

आप अपने AJAX कोड को एक अलग फ़ंक्शन में रख सकते हैं और जब भी कोई अनुरोध समाप्त होता है तो वह इस पद्धति को कॉल कर सकता है और अपनी पहचान पास कर सकता है जिसे अगले अनुरोध के लिए बढ़ा दिया जाएगा।


उत्तर № 3 के लिए 1

$ .When () आज़माएँ

var requests = $.map(array, function (i, item) {
return ajax_request(item.id, item.title, i);
});
$.when.apply($, requests).done(function(){
$.each(arguments, function(i, params){
var data = params[0];
//do your stuff
})
})

function ajax_request(id, title, i) {
return $.ajax({
async: false,
url: "url here"
})
}