Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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. :-)


There 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.


Fixed!

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-typo...

Task.WaitAll is the C# equivalent: 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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: