Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I realize pattern promise/defered?

Tags:

c#

promise

I want to write a pattern Promise/Deffered. Perfect variant in end is:

MyObject().CallMethodReturningPromise()
   .done( result => {
       ...something doing;
   } )
   .fail( error => {
       ...error handle;
   } )
   .always( () => {
       ...some code;
   } )

I've found this implementation https://bitbucket.org/mattkotsenas/c-promises/overview and https://gist.github.com/cuppster/3612000. But how can I use it to solve my task???

like image 512
Multix Avatar asked Oct 01 '14 07:10

Multix


People also ask

What is the difference between a deferred and a promise?

A promise represents a value that is not yet known. This can better be understood as a proxy for a value not necessarily known when the promise is created. A deferred represents work that is not yet finished. A deferred (which generally extends Promise) can resolve itself, while a promise might not be able to do so.

What is deferred in promise?

The deferred. promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request.

How do you get promise data resolved?

Consider the following code snippet: let primise = new Promise((resolve, reject) => { resolve({ x: 10 }); }); setTimeout(() => { // At some moment in the future (Promise is resolved) console. log(promise); }, 200); Now, the promise was resolved with { x: 10 } .

How do you wait for promises to resolve before returning?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.


2 Answers

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. 
like image 81
Benjamin Gruenbaum Avatar answered Sep 29 '22 09:09

Benjamin Gruenbaum


Seems to me, this perfectly fit with tasks:

var deferred = Task     .Factory     .StartNew(() => /* produce some result (promise) */);  // done deferred     .ContinueWith(d => Console.WriteLine(d.Result), TaskContinuationOptions.OnlyOnRanToCompletion);  // fail deferred     .ContinueWith(d => Console.WriteLine(d.Exception), TaskContinuationOptions.OnlyOnFaulted);  // always deferred     .ContinueWith(d => Console.WriteLine("Do something")); 
like image 20
Dennis Avatar answered Sep 29 '22 09:09

Dennis