C# solves this with Task
s
Tasks solve the same problem as promises do in JavaScript - and you can use them similarly. However normally, you shouldn't.
There are several differences:
- Tasks have cancellation built in.
- Tasks aren't always started, and you can have tasks and start them later.
- Promises perform assimilation, you can't have a
Promise<Promise<T>>
but you can have a task of a task in C# and might need to call .Unwrap
on tasks.
- There is one canonical implementation of tasks in the TPL (task parallelization library) that ships with C# but many implementations of promises in JavaScript.
Using Tasks
Here's how you'd use them with the async/await
syntax - which will be added to JavaScript in ES7 and can be used in ES6 with yield
in some libraries.
async Task Foo(){
try{
var res = await myObject.CallMethodReturningTaskOrAsyncMethod();
doSomethingWithResponse(res);
} catch(e){
// handle errors, this will be called if the async task errors
} finally {
// this is your .always
}
}
You can also use .ContinueWith
which parallels to .then
but it's very uncommon in C# and is generally frowned upon when await can be used. You can learn more about using async
/await
here.
Deffereds are mapped to TaskCompletionSource
instances and Promise
s are Task
s in C#. Task.WhenAll
is used where you'd use $.when
or Promise.all
.
Where you'd usually write:
a().then(function(res){
return b(res, "foo");
}).then(function(res2){
// do work on res2
});
You'd do the following in C#:
var res = await a();
var res2 = await b(res, "foo");
// do work on res2.