I would like to fetch data from multiple locations from
Firebase Realtime Database like described here and here by Frank van Puffelen and I can't find any equivalent to Promise.all
in c#. What would be the proper way to do it?
Asked
Active
Viewed 1.4k times
16

Mauricio Gracia Gutierrez
- 10,288
- 6
- 68
- 99

Dave
- 2,684
- 2
- 21
- 38
-
2In addition to any answers here, check out [this SO answer explaining a Promise equivalent in C#](https://stackoverflow.com/a/38998516/5803406) – devNull Feb 02 '19 at 18:08
2 Answers
24
That you are looking for is Task.WhenAll. You should create as many tasks as the multiple locations from which you want to fetch your data and then feed them in this method.

Christos
- 53,228
- 8
- 76
- 108
-
1I think Task.WhenAll is similar to Promise.allSettled, not Promise.all. There is nothing in .NET similar to Promise.all as far as I know. – Sake Feb 26 '22 at 12:43
-
Here's [the example](https://stackoverflow.com/a/17197786/283851) that probably should have come with this answer. As @Sake pointed out, this is more similar to `Promise.allSettled` than `Promise.all` - because of static typing, if you have `Task
` instances with different types `T`, something like `Promise.all` would lead you into type-casts, which is clunky and unsafe; you're better off with something like `Promise.allSettled` and simply await again for the results from the tasks that have already been run and resolved in parallel. It's all good. :-) – mindplay.dk Aug 01 '22 at 07:31
7
To expand on @Christos's accepted answer:
Task.WhenAll appears to be about as close as you will get for a drop-in replacement for Promise.all. I actually found it to be closer than I initially thought. Here's an example using a JavaScript Promise.all
implementation that you may want to replicate in C#:
const [ resolvedPromiseOne, resolvedPromiseTwo ] = await Promise.all([ taskOne, taskTwo ]);
In C# you can do something very similar with Task.WhenAll
(assuming they return the same types).
var taskList = new[]
{
SomeTask(),
AnotherTask()
};
var completedTasks = await Task.WhenAll(taskList);
// then access them like you would any array
var someTask = completedTasks[0];
var anotherTask = completedTasks[1];
// or just iterate over the array
foreach (var task in completedTasks)
{
doSomething(task);
}
This assumes they're both in async
methods / functions.

Bryantee
- 474
- 1
- 6
- 12
-
these seems to be either obsolete or for a earlier version of .NET than my env. – Mauricio Gracia Gutierrez Aug 05 '21 at 00:33
-