6 features of JavaScript asynchronous programming promise Patterns

Source: Internet
Author: User

 promise is a very simple concept, and even if you don't have a chance to use it, chances are that you've learned about it. Promise is a valuable constructor that can help you avoid using nested anonymous methods and assemble asynchronous code in a more readable way. Here we will introduce the 6 simplest features that we would like to help you with.

Before we begin our formal presentation, we'd like to look at the JavaScript Promise:   code as follows: var p = new Promise (function (resolve, reject) {  Resolve ("Hell O World "); });   P.then (function (str) {  alert (str);}); 1. Then () What is the difference between returning a forked Promise   The following two paragraphs of code?   Code as follows://Exhibit A var p = new Promise (/*...*/); P.then (FUNC1); P.then (FUNC2);  //Exhibit B var p = new Promise (/*...*/); P.then (FUNC1). then (FUNC2); If you're serious about the two pieces of code that are equivalent, then promises is just a one-dimensional array of callback functions. However, this is not the case. Each then () call returns a forked promise. Therefore, in Exhibita, if Func1 () throws an exception, Func2 () is still called normally.   in EXHIBITB, if Func1 () throws an error, fun2 () will not be invoked because the first call returns a new promise, which is rejected in Func1 (). The result is that Func2 () is skipped.   Summary: Promises can be fork into multiple paths, similar to complex flowcharts.   2. Callback should deliver results   what will get a warning when you run the following code?     Code is as follows: var p = new Promise (function (resolve, reject) {  Resolve ("Hello World");});   P.then (function (str) {}). then (function (str) {  alert (str);}); Alert in the second then () does not display any content. This is because the callback function, in the context of the promise, has no callback function because of the change in the result. Promise expects your callback function to return the same result or to return a replacement knotAnd is then passed to the next callback function.   Similar to using adpater to change results, as follows:     code is as follows: var feettometres = function (ft) {return ft*12*0.0254};   var p = new Promise (/*...*/);   P.then (feettometres). Then (function (metres) {  alert (metres);});   3. Only the exception from the previous layer can be captured   what is the difference between the two pieces of code?     Code as follows://Exhibit A new Promise (function (resolve, reject) {  Resolve ("Hello World"); then (  FU Nction (str) {    throw new Error ("Uh oh");  },   undefined). Then (  Undefined,   functio N (Error) {    alert (error);  });    //Exhibit B new Promise (function (resolve, reject) {  Resolve ("Hello World"); then (  functio N (str) {    throw new Error ("Uh oh");  },   function (Error) {    alert (error);  }) ;   In the first code, the exception in the first then () is thrown, will be caught by the second then (), and the "Uh Oh" warning will be triggered. This follow only the previous level of the exception will be captured.   In the second code, the callback function and the error callback function are at the same level, meaning that when the exception is thrown in the callback, it will not be captured. In fact, the error callback for the second piece of code will only be in the promise State or promiseitself in case of error thrown   4. Errors can be restored   in an error callback function, if you do not throw the error back, promise assumes that you have recovered from the error and that the reversal has been resolved. In the next example, "I ' M saved" will be displayed because the error callback in the first then () does not throw the exception back.   Code as follows: var p = new Promise (function (resolve, reject) {  Reject (new Error ("Pebkac");});   P.then (  Undefined,   function (Error) {}). Then (  function (str) {    alert ("I am Save D! ");  },   function (Error) {    alert ("Bad computer!");  }); Promise can be seen as layers on onions. Each then () adds another layer to the onion. Each level represents an activity that is handled. When the hierarchy is over, the result is thought to have been repaired and ready for the next level.   5. Promises can be paused   because you are ready to execute in a then () method does not mean that you are not able to pause and run the others ahead of time. In order to suspend the current promise, or let it wait for another promise to complete, simply return another promise in then ().   Code as follows: var p = new Promise (/*...*/);   P.then (function (str) {  if (!loggedin) {    return new Promise (/*...*/);  }}). Then (function (str) {  alert ("done.");}) In the preceding code, the prompts do not appear until the new promise resolves. This is a convenient way to introduce more dependencies in an existing asynchronous code path. For example, you may find that the user session has been timeout, and you may want to initialize the second login before continuing the previous code path. &nBsp 6. Resolved promises will not execute immediately   run the following code will get a hint box?   Code as follows: function Runme () {  var i = 0;     New Promise (function (resolve) {    resolve (); nbsp })  . Then (function () {    i + 2;  });   alert (i); Because promise is parsed immediately, then the then () method is executed immediately, so you may think that Tip 2 will be detected. However, the promise definition requires that all calls be coerced asynchronously. Therefore, the prompts are generated before being modified.  
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.