यह उत्तर मानक promisesकी एक जावास्क्रिप्ट सुविधा का उपयोग करता है ECMAScript 6। यदि आपका लक्ष्य प्लेटफ़ॉर्म समर्थन नहीं करता है promises, तो उसे PromiseJs के साथ पॉलीफ़िल करें ।
जावास्क्रिप्ट में अतुल्यकालिक संचालन को संभालने के लिए वादे एक नया (और बहुत बेहतर) तरीका है:
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable).then(function() {
//this function is executed after function1
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});
function function1(param, callback) {
return new Promise(function (fulfill, reject){
//do stuff
fulfill(result); //if the action succeeded
reject(error); //if the action did not succeed
});
}
यह इस सरल उदाहरण के लिए एक महत्वपूर्ण ओवरहेड की तरह लग सकता है, लेकिन अधिक जटिल कोड के लिए यह कॉलबैक का उपयोग करने से कहीं बेहतर है। आप कई thenबयानों का उपयोग करके आसानी से कई अतुल्यकालिक कॉल को चेन कर सकते हैं :
function1(someVariable).then(function() {
function2(someOtherVariable);
}).then(function() {
function3();
});
आप आसानी से jQuery deferrds को भी लपेट सकते हैं (जो $.ajaxकॉल से वापस आ जाते हैं):
Promise.resolve($.ajax(...params...)).then(function(result) {
//whatever you want to do after the request
});
जैसा कि @charlietfl ने उल्लेख किया है, jqXHRऑब्जेक्ट इंटरफ़ेस को $.ajax()लागू करता Promiseहै। तो यह वास्तव में इसे में लपेटने के लिए आवश्यक नहीं है Promise, इसे सीधे इस्तेमाल किया जा सकता है:
$.ajax(...params...).then(function(result) {
//whatever you want to do after the request
});
function1एक async कार्रवाई करते?