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?
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With