Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine asynchronous calls with synchronous in javascript

Tags:

javascript

I'm kind of beginning to learn javascript and have a question about combining synchronous and asynchronous calls to functions. This will be just a theoric problem, but I hope it transmits the idea.

Let's suppose we have javascript program that decides how many bananas and oranges I need to buy.

console.log('buy %d bananas and %d oranges', bananas, oranges)

Now, I can decide how many bananas I can buy, but I need to ask my wife how many oranges she wants, so I text her. (I can write an async function to represent this).

This would be my immediate approach:

var bananas = 10;
var oranges = 0;
textWife('askAboutOranges',function(number){ oranges = number; }
console.log('buy %d bananas and %d oranges', bananas, oranges)

But to me this doesn't make sense, because I have to wait for my wife to reply, so I probably won't have the number of oranges in time.

So I can change my program to:

var bananas = 10;
var oranges = 0;
textWife('askAboutOranges',function(number){ 
   oranges = number;
   console.log('buy %d bananas and %d oranges', bananas, oranges); 
}

But I don't like this because now I have the logic of deciding what to buy including the bananas, inside the response from my wife. What if I decide I don't want oranges, do I have to do something like this:

var bananas = 10;
var oranges = 0;
if (wantOranges)
{
  textWife('askAboutOranges',function(number){ 
   oranges = number;
   console.log('buy %d bananas and %d oranges', bananas, oranges); 
  }
}
else 
  console.log('buy %d bananas and %d oranges', bananas, oranges); 

So my question is, can anyone explain me what's the best/right way to do something like this?

like image 733
Joao Leal Avatar asked Jul 09 '13 22:07

Joao Leal


1 Answers

jQuery Deferred is a great tool to have in your belt. I might do something like this to separate concerns:

function decideHowManyBananas() {
    return 10;
}

function decideHowManyOranges() {
    var deferred = $.Deferred();

    if (wantOranges) {
        textWife('askAboutOranges', function(number) { 
            deferred.resolve(number);
        });
    } else {
        deferred.resolve(0);
    }

    return deferred.promise();
}

$.when(decideHowManyBananas(), decideHowManyOranges()).done(function(bananas, oranges) {
    console.log('buy %d bananas and %d oranges', bananas, oranges);
});
like image 78
Jason P Avatar answered Sep 22 '22 10:09

Jason P