How can I realize pattern promise/defered?

C# solves this with Tasks

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 Promises are Tasks 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)