1

My question totally depends on a previous question:

Regarding approach number 3 (the "counter" one): If handleCompletion needs a value from startOtherAsync in order to do its job. How can we implement that?

Note that that value coming from startOtherAsync (probably a parameter) will make startAsync sad and unable to call handleCompletion anymore.

4
  • 1
    sounds to me like you'd want to use promises via jQuery's Deferred object. Commented Jan 28, 2014 at 2:54
  • Maybe that's right. I'm looking into it, I haven't used it before. Commented Jan 28, 2014 at 2:59
  • Also, can you explain what value needs to be passed from startOtherAsync? Commented Jan 28, 2014 at 3:31
  • @Jack: Technically startOtherAsync will pass nothing. but the success of his ajax call will call back handleCompletion passing the returned ajax value. Commented Jan 28, 2014 at 3:42

1 Answer 1

2

This is actually a perfect place to use promises. All the jQuery Ajax calls return promises by default which means you can simply chain them together:

$.ajax({/*snip*/}).then(
   function(result){

      doSomethingWithResult(result);

      return $.ajax({/*snip*/});

   }).then(function(result){

      doSomeFinalProcessing(result);

   });

And of course, a jsFiddle to demonstrate this happening.

Here is an updated fiddle that shows how to combine multiple simultaneous promises and combine their results.

http://jsfiddle.net/jwcarroll/U3N9u/

And the code:

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

function doStuffLater(msg){
    var def = $.Deferred();

    setTimeout(function(){

        def.resolve(msg);

    }, getRandomInt(300, 1000));

    return def.promise();
}

function needsBothReturns(one, two){
    console.log({one:one, two:two});
}

var first = doStuffLater("Sent First");
var second = doStuffLater("Sent Second");

$.when(first, second).done(function(result1, result2){
    needsBothReturns(result1, result2);
});
Sign up to request clarification or add additional context in comments.

3 Comments

It looks like this implements a callback chain not separate async functions with a third waiting function.
@yazanpro - If you look at the fiddle, each call to doSomething later is indeed asynchronous. You can also create your own deferred if you need to execute to things simultaneously.
Yeah, That's pretty clear now. It addresses my problem and I realized the concept as well. Thank you for your update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.