From C # to Typescript-promise

Source: Internet
Author: User

From C # to typescript-promise backgrounds

I believe that friends who have used JavaScript before have encountered asynchronous callback Hell (callback Hell), n multiple callback nesting not only makes the code read very difficult, maintenance is also very inconvenient.
In fact, C # Task before the advent of a similar scenario, the Async Programming mode era, with Action and Func do callbacks are also very popular, but also aware that too many callback nesting code is poor readability and maintenance is not easy, Microsoft introduced Task and task-based Async Pattern.
Although it is not known which language is the first to have this concept, but it is believed to be C # to the async await popular language stage, and then other languages are supported in different forms async await , such as Python, Dart, Swift and so on.
JavaScript also began to support and ES6 in the Promise Generator ES7, and proposed a supportive motion in the middle async await .

This article first looks at promise:

Features of Promise

PromiseTo Typescript, which is equivalent Task to C #, only Promise the returned function can be used async await .
Promiseis actually an object that can get asynchronous results and encapsulate some of the asynchronous operations.
There are three states:
pending: In progress
resolved: Success
rejected: Failed
And there are only two transitions in these three states pending : resolved pending rejected ----------not success is failure, and there is no redundant state transitions.
Both of these conversions are given by the result of the asynchronous return, and the successful retrieval of the data is the resolved exception to the data rejected .
Therefore, the result of this conversion is fixed, it is not possible to change back pending or other state after the conversion.
PromiseCannot be canceled in the task, can only wait for the results to return, this is not as good as C # Task , Task you can CancelTaskToken cancel the task by.

Use of Promise

You can directly new an Promise object, and the constructor's argument is a function with two parameters.
One of these two parameters is resove used to call after the asynchronous operation succeeds, and the asynchronous result is sent out, and the resove state is called pending resolved .
The other is that it is reject used to invoke at the time of failure or exception, and to send out the error message, after the call reject state pending rejected .

var promise = new Promise(function(resolve, reject) { });

Usually need to do after success or failure to do something, then you need to do this, then you can have two function parameters, the first one is a successful call, the second is a failed call, the second is optional.
In addition, the then return is also a promise, but not the original, but the new come out, so you can chain call, followed by the then next then .

// 函数参数用lambda表达式写更简洁promise.then(success => {    console.info(success);}, error => {    console.info(error);}).then(()=>console.info(‘finish‘));
Nested promise

In a real-world scenario, we might need to take an asynchronous operation after an asynchronous operation, which would have Promise nested operations.
The following code shows the Promise nested operation:
p1Print "Start" first, two seconds delay to print "P1".
p2p1after completion, the delay is two seconds to print "P2".

functiondelay (promise< void>{return new Promise<< Span class= "hljs-built_in" >void> ((Resolve, Reject) =>{settimeout (() =>resolve (), 2000)}); let p1 = new Promise ((Resolve, reject) + = {console.info (console.info ( ' P1 '); resolve ()});}); let p2 = new Promise ((resolve, reject) = {P1.then (() = = Delay (). Then (() =>resolve ());}); P2.then (() =>console.info ( ' P2 '));     
Exception handling

The above mentioned Promise error when the state is changed rejected and the error message to the reject function, then inside the reject function can be called to show the exception.
However, this is not very friendly, and Promise there is a catch function specifically to handle error exceptions.
and Promise the exception is bubbling pass, the last write one catch can capture to the previous all promise possible exception, if you reject need to write each.
So the reject function generally does not need to write in it then , in the back with a catch can.

new Promise(function(resolve, reject) {  throw new Error(‘error‘);}).catch(function(error) { console.info(error); // Error: error});

As stated above there are only two changes and once the change is fixed, so if it has been Promise executed in resolve , then throw the exception is useless, catch not, because the state has become resolved .

new Promise(function(resolve, reject) {    resolve(‘success‘); throw new Error(‘error‘);}).catch(function(error) { console.info(error); // 不会执行到这里});

In addition, catch the code may be abnormal, so catch the following can also follow catch the motion.

new Promise (function (resolve, reject) {throw new error (function (error) {console.info (Error); //error:error throw new error ( ' catch Error ');}). catch (function (error) {console.info (Error); //error:catch Error};           
Finally and done for Bluebird

The exception try...catch can be followed finally to execute the code that must be executed, the Promise native does not support, you can introduce Bluebird extension library to support.
There is also the done last side to indicate the end of execution and throw a possible exception, such as an catch exception in the last block of code.

Let p =New Promise (functionResolve, Reject) {x = 2; //error, no declaration of X variable resolve (' success ');}). catch (function (error) { console.info (error);}). Finally (() =>{ //always executes here Console.info (' finish '); y = 2; //error, no y variable declared}). Done (); try{p.then (() =console.info (' done ');} catch (E) { console.info (e); //Due to the last done, the exception in finally is thrown, and if there is no do it will not be executed here}           
Parallel execution Promise

Although JavaScript is a single-threaded language, it does not prevent it from performing some IO parallel operations, such as not blocking the issue of HTTP request, and then waiting asynchronously.
PromiseIn addition to then sequential execution, the same can be done without blocking simultaneous execution of multiple Promise and then all results returned and then subsequent operations.
C # Task has a WhenAll static method to do this, it Promise is to use the all method to achieve the same purpose.
allThe iterator method accepts objects that implement the interface, such as arrays.

let p = Promise.all([p1, p2, p3]);

allThe return is a new Promise -p,p state is determined by P1, P2, p3 at the same time:

p.resolved = p1.resolve && p2.resolve && p3.resolvep.rejected = p1.rejected || p2.rejected || p3.rejected

That is to say, P's success requires P1,P2,P3 success, and as long as P1, p2, P3 has any failure in the P failure and exit.

PromiseThere is also a way to race execute multiple in parallel Promise , different from all its success state and error state, as long as there is a successful success, like the method of C # task Any .

From C # to Typescript-promise

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.