JavaScript ES6 Promiss's understanding.

Source: Internet
Author: User

In the spirit of sharing the Internet, I will share my understanding of promise to you.

The Promise method of JavaScript ES6 is mainly applied to the result of handling the return of an asynchronous function, noting that he is not converting an asynchronous function to a synchronous function, but when the asynchronous function has the result when the corresponding method is called to process.

Promise has the following methods

Then ()-it requires a maximum of two parameters, the first is the method to be called after success, and the second is the method that is called after the failure.

catch ()-a method that is called after a failure, similar to the method that was called after the failure of the then method, but there are some differences in usage, so I'll use the case to explain.

All ()-takes an array as an argument, and the array can fill in an asynchronous function, and when all of the asynchronous functions are executed, a promise array is returned. One thing to note, however, is that there is a method in the parameter to get an error and he will make an error and will not return the result.

Race ()-He also accepts an array as a parameter (as well as the method of all) (also such as if there is a method error in the array then he will error, will not return the result), but a little different is to return only one result, that is, which function is the first to complete the return of the result.

Resolve ()-and then, like the first parameter, returns a promise successful Call method.

Reject ()-like the second parameter of then, returns a method that is called after a promise failure.

A vicious set of asynchronous callbacks.

In this case, I used a timer to simulate an AJAX server asynchronous request.

function Fun (A, B, CB) {    setTimeout(function  () {        + b)    )}fun (1, 2 ,function  (result) {    Console.log (Result)}), Console.log (/////  This will first output 5 in the output 3 

In a more complex case, it's definitely a callback set, so it's certainly not the wrong code to execute, but it's not logically clear.

 function   Fun (A, B, CB) {setTimeout ( Span style= "COLOR: #0000ff" >function   () {CB (a  + b)},  1000)}fun ( 1, 2, function   (Result) { if  (Result > 1" {Fun (result,  2, function   (Result)                {Fun (result,  3, function   (Result) { Console.log ( ' completed ' 5); //  This will output 5 at output completion 8  
Use the Promise method to rewrite the above case-then
functionFun (A, b) {return NewPromise (function(Resolve, Reject) {SetTimeout (function() {Resolve (a+b)},1000)})}fun (1, 2). Then (function(Result) {if(Result > 1) {            returnFun (Result, 2)}). Then (function(Result) {if(Result > 1) {            returnFun (Result, 3)}). Then (function(Result) {Console.log (Complete, result)});
Using the then method to handle error failures

Then the first parameter is the method used to handle promise success, the second parameter is the method after the promise process fails, and the following case I will simulate the error.

If the parameter passed in the fun function is not of type number, then the error handler of the then method is triggered, that is, the second function, and of course the first function is not executed.

functionFun (A, b) {return NewPromise (function(Resolve, reject) {if(typeofA!== ' number ' | |typeofb!== ' number ') {Reject (NewError (' No number ')} setTimeout (function() {Resolve (a+b)},1000)})}fun (1, ' 1 '). Then (function(Result) {if(Result > 1) {            returnFun (Result, 2)        }    }, function(ERR) {//This method will be executed because of the error, well understoodConsole.log (ERR)}) . Then (function(Result) {Console.log (' second Then ');//output Second Then if the wrong method in the first then is used properly, it will not affect here, but I did not do the corresponding processing just output err, result returns the method in Undefined,if will not be executed.         if(Result > 1) {            returnFun (Result, 3)        }    });

Using catch to catch error-use of Catch method

The then method is run from top to bottom, and if there is an error in the run then the then method stops running at the error and calls the wrong method. Note: Unlike the then method, then the processing mechanism will continue to execute down, and the catch will not, skip the non-executed then directly into the catch

functionFun (A, b) {return NewPromise (function(Resolve, reject) {if(typeofA!== ' number ' | |typeofb!== ' number ') {Reject (NewError (' No number ')} setTimeout (function() {Resolve (a+b)},1000)})}fun (1, 1). Then (function(Result) {if(Result > 1) {Console.log (1)//1 normal output. returnFun (result, ' 2 ')//Here 2 is not a number type. }}). Then (function(Result) {//Because the parameter passed in above is not a number type, then this will invoke error handling, that is, the catch method is executed.
Console.log (2)//Do not executeif(Result > 1) { returnFun (Result, 3)}). Then (function(Result) {
Console.log (3)//does not perform console.log (Complete, result)}) .Catch( function(Err) {Console.log (ERR)});
What happens if I use the second parameter of catch and then to capture parameters at the same time?

If the then method has a second argument then the catch is not executed and the second argument is executed. Catch can be understood as a tray, if then there is no way to deal with the error, then the method in the catch will be executed, if there is no then the second method and catch then will not error, because there is no wrong processing mechanism then will not be the errors.

functionFun (A, b) {return NewPromise (function(Resolve, reject) {if(typeofA!== ' number ' | |typeofb!== ' number ') {Reject (NewError (' No number ')} setTimeout (function() {Resolve (a+b)},1000)})}fun (1, ' 1 '). Then (function(Result) {if(Result > 1) {            returnFun (Result, 2)        }    }, function(ERR) {//Execute output No number +12 Console.log (Err+ ' 12 ')}). Then (function(Result) {Console.log (' Second Then '); Execution output Second thenif(Result > 1{//This will not be performed because there is no result because result is undefined if it is handled properly within the first then processing method, it can be executed here. returnFun (Result, 3)        }    })    .Catch(function(ERR) {//Will not execute here, because each then has its own handling, so the catch will not be executed. Console.log (Err+ ' I am the catch's error handling ')    });

JavaScript ES6 Promiss's understanding.

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.