C# – Problem with async/await pattern — in C# and JavaScript — how to return sync value

asyncc

In old-style await'less NodeJS, when you call a function that had an asynchronous aspect, you'd pass in the well-known callback which gets called when the asynchronous portion is done. This didn't pollute the return value of the function whereas the function can still return something meaningful to the caller synchronously.

The problem with the async/await pattern now is that to use it, you have to decide if a function is synchronous or asynchronous. This means that if I have an existing function that's synchronous, and has a return value that will remain synchronously calculated and thus returned when the function returns, and I want to add an asynchronous component to it, previously I would add a callback, and change the callers. But now I have to make the return value the asynchronous value and the original return value — find another way. What would that be?

Would you use an 'out' parameter in C#? That's not a best-practice.
Would you pass in an object whose state you modify to return the sync value?

The current trend is return a tuple, and object with multiple values. But can one of those values by synchronous and the other asynchronous?

Best Answer

Why can't you return an already completed task?

C#: return Task.FromResult(...);

JavaScript: return Promise.resolve(...);

In fact, C# recently added ValueTask<T> to avoid allocations for this scenario where a value is available immediately.