Skip to content Skip to sidebar Skip to footer

Two Parallel Calls Either One Succeeds In Javascript

I want something like the async library to do two parallel calls either one succeeds in javascript and then the callback to operate on the succeeded output. It does not seem that a

Solution 1:

You can use jQuery.Deferred and jQuery.when to achieve this (there are other promise libraries too).

var d1 = $.Deferred();
var d2 = $.Deferred();

$.when( d1, d2 ).done(function ( v1, v2 ) {
   // this will execute only when both deferred objects are resolved// and the values passed to those for resolving will be available // through v1 and v2
});

$.get('url1').success(function() { d1.resolve('value for v1') });
$.get('url2').success(function() { d2.resolve('value for v2') });

jQuery.when: https://api.jquery.com/jQuery.when/

jQuery.Deferred: https://api.jquery.com/category/deferred-object/

Post a Comment for "Two Parallel Calls Either One Succeeds In Javascript"