I'm writing a web page, and it calls some web services. The calls looked like this:
var Data1 = await WebService1.Call(); var Data2 = await WebService2.Call(); var Data3 = await WebService3.Call();
During code review, somebody said that I should change it to:
var Task1 = WebService1.Call(); var Task2 = WebService2.Call(); var Task3 = WebService3.Call(); var Data1 = await Task1; var Data2 = await Task2; var Data3 = await Task3;
Why? What's the difference?
The await operator is used to wait for a Promise . It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.
Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
The await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes. When the asynchronous operation completes, the await operator returns the result of the operation, if any.
Answers. Always follow the standard async/await programming pattern from top down. Do not use . Result() as it is only used to invoke an async method from synchronous code.
Servy's answer is correct; to expand on that a little. What's the difference between:
Eat(await cook.MakeSaladAsync()); Eat(await cook.MakeSoupAsync()); Eat(await cook.MakeSandwichAsync());
and
Task<Salad> t1 = cook.MakeSaladAsync(); Task<Soup> t2 = cook.MakeSoupAsync(); Task<Sandwich> t3 = cook.MakeSandwichAsync(); Eat(await t1); Eat(await t2); Eat(await t3);
?
The first is:
Your second program is equivalent to:
You see the difference? In your original program you don't tell the cook to start the next course until you are done eating the first course. In your second program you request all three courses up front, and eat them -- in order -- as they come available. The second program makes better use of the cook's time because the cook can "get ahead" of you.
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