I'm kind of starting to learn javascript and wondering about combining synchronous and asynchronous calls with functions. This will only be a theoretical problem, but I hope that it conveys this idea.
Suppose we have a 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 set out. (I can write an async function to represent this).
This will 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 for me this does not make sense, because I have to wait until my wife answers, so I probably will not have the number of oranges on time.
Therefore, 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 do not like it, because now I have the logic of deciding what to buy, including bananas, in response from my wife. What if I decide I donβt want oranges, I need 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 someone explain to me what is the best / right way to do something like this?