31

With the addition of async / await to TypeScript using Promise(s) can look very syntactically close to Task(s).

Example:

Promise (TS)

public async myAsyncFun(): Promise<T> {
    let value: T = await ...
    return value;
}

Task (C#)

public async Task<T> MyAsyncFun() {
    T value = await ...
    return value;
}

I was wondering if the other way around, there was an equivalent to .then() for Task(s).

Example:

Promise (TS)

Promise<T> promise = ...
promise.then((result: T) => ...do something...);
1

2 Answers 2

24

I've used ContinueWith which can work if you have one or multiple Tasks running.

example:

public async Task<T> MyAsyncFun() {
    T value = await ...
    return value;
}

MyAsyncFun().ContinueWith(...

https://msdn.microsoft.com/en-us/library/dd270696(v=vs.110).aspx

3
  • So would it look like: Task<T> task = await ... task.ContinueWith((task, result) => ...do something...); Commented Dec 15, 2016 at 20:30
  • Updated my answer Commented Dec 15, 2016 at 20:31
  • Thank you, Sorry I submitted my first comment without finishing it. Commented Dec 15, 2016 at 20:34
3

You can create a handy extension method for task continuations to match the javascript .then function. I find it easier to use than .ContinueWith, which has its own set of pitfalls and encumbrances.

public static class TaskExtensions
{
    public static async Task<TV> Then<T,TV>(this Task<T> task, Func<T,TV> then)
    {
        var result = await task;
        return then(result);
    }
}

Then you can use it like so

Task<User> userRecord = GetUserById(123)
Task<string> firstName = userRecord.Then(u => u.FirstName)
5
  • 1
    The await task might need to be configured with .ConfigureAwait(false), or might not, depending on where you want to invoke the then lambda. So this is not a good operator for general use. Related GitHub API proposal: Then or ContinueWithResult extension method for Task. Commented Nov 17, 2022 at 23:01
  • If you care about .ConfigureAwait, you can add an optional parameter to the extension method. Commented Nov 17, 2022 at 23:05
  • And what would be the default value of the optional parameter? Commented Nov 17, 2022 at 23:11
  • true since that's the default .ConfigureAwait value if you choose not to use .ConfigureAwait Commented Nov 17, 2022 at 23:18
  • Then it would not be consistent with the default of the popular Polly library. Commented Nov 18, 2022 at 0:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.