7 ms·
Does C# not have an equivalent to JavaScript's Promise.all?? In JS this could be... const [ fooTask, barTask, bazTask, ] = await Promise.all([
by itslennysfault 5y ago
Does C# not have an equivalent to JavaScript's Promise.all??
In JS this could be...
const [
fooTask,
barTask,
bazTask,
] = await Promise.all([
GetFooAsync(...),
GetBarAsync(...),
GetBazAsync(...)
]);
... PS in your code above you assign GetBazAsync to bar and baz. :-)
- jiggawatts 5y agoFixed! I believe this kind of copy-paste "last line effect" one of the most common errors in programming: https://hownot2code.com/2016/08/15/the-last-line-effect-typos-and-fun/ https://hownot2code.com/2016/08/15/the-last-line-effect-typo... Task.WaitAll is the C# equivalent: https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.waitall https://docs.microsoft.com/en-us/dotnet/api/system.threading... But it's not necessarily faster, there are corner cases where waiting for all tasks prevents some concurrent computations (e.g.: JSON parsing) from occurring.
- contextfree 5y agoThere is Task.WhenAll which works similarly, but the problem is that it requires either all of the tasks to have the same return type, or else treat all the tasks in the array as untyped and extract the return values in a separate step. i.e. you have to write var (fooTask, barTask, bazTask) = (GetFooAsync(), GetBarAsync(), GetBazAsync()); await Task.WhenAll(fooTask, barTask, bazTask); var (foo, bar, baz) = (fooTask.Result, barTask.Result, bazTask.Result); It's possible to write a custom awaiter extension method that allows awaiting tuples of tasks, so once that's in place you can just write var (foo, bar, baz) = await (GetFooAsync(), GetBarAsync(), GetBazAsync()); There are third-party packages that do this for you and it's reasonably easy to write yourself if you understand the inner workings of async/await, but it's not part of the standard library.