How to Use Promise in Asynchronous JavaScript programming _ node. js? 1.1.5

Source: Internet
Author: User
This article mainly introduces the use of Promise in Asynchronous JavaScript programming, including the combination of Ajax operations and other issues. For more information, see Asynchronous?

I have seen Asynchronous in many places, but when I am not very familiar with this concept, but they often think that they are "already clear" (*  ̄? ).

If you have a similar situation, it doesn't matter. Search for the word to give a rough description. Here, I will explain JavaScript Asynchronization a little bit.

Take a look at this Code:

var start = new Date();setTimeout(function(){  var end = new Date();  console.log("Time elapsed: ", end - start, "ms");}, 500);while (new Date - start < 1000) {};

After this code is run, the result is like Time elapsed: 1013ms. SetTimeout () indicates the function to be executed in the Next Ms. It is executed only after more time than Ms.

How to explain it? When setTimeout () is called, a latency event is queued. Then, continue executing the code after this and the code behind it until there is no code. When no code is available, the JavaScript thread enters Idle State. At this time, the JavaScript execution engine looks at the queue and finds the event that should be triggered in the queue, and then calls the processor (function) of the event ). After the processor completes execution, return to the queue and view the next event.

Single-threaded JavaScript works in the form of event loops through queues. Therefore, in the previous code, while is used to drag the execution engine for up to 1000 ms during code running, and no event will be triggered until all the code is run back to the queue. This is the asynchronous mechanism of JavaScript.
Asynchronous JavaScript Problems

Asynchronous operations in JavaScript may not always be simple.

Ajax may be the most widely used asynchronous operation. Taking jQuery as an example, the code that initiates an Ajax request is generally as follows:

// Ajax Request Code $. ajax ({url: url, data: dataObject, success: function () {}, error: function (){}});

Is there any problem with this writing? In short, it is not light enough. Why should we write the success and error callbacks at the place where the request is initiated? If my callback has to do a lot of things, do I need to remember one thing and run back here to add code?

For another example, we need to do this: There are four URLs for Ajax access. Ajax needs to access 1st URLs first. After 1st URLs are complete, use the returned data as the parameter to access 2nd more, and 2nd more after 3rd accesses are completed... in this way, all four accesses are completed. It seems like this:

$.ajax({  url: url1,  success: function(data){    $.ajax({      url: url2,      data: data,      success: function(data){        $.ajax({          //...        });      }      });  }})

You will surely think this kind of code called Pyramid of Doom looks terrible. Having used to directly append callback, you may feel unable to start with such an asynchronous event passed to the next one. Naming and separating these callback functions can reduce nesting in form, so that the code is clear, but the problem still cannot be solved.

Another common difficulty is to send two Ajax requests at the same time, and then do the following after both requests are successfully returned, think about it if you only append the callback in the previous method in their respective call locations, isn't it a little difficult?

To cope with these asynchronous operations, you can write more elegant code by using Promise.
Promise on stage

What is Promise? Let's continue with the previous jQuery Ajax request sample code. The code can actually be written like this:

var promise = $.ajax({  url: url,  data: dataObject});promise.done(function(){});promise.fail(function(){});

This is equivalent to the preceding Ajax request signal code. As you can see, the addition of Promise changes the code format. The Ajax request is "saved" like a variable value assignment. This is encapsulation, which makes asynchronous events easy in the true sense.
Encapsulation is useful

The Promise object is like a encapsulated reference to asynchronous events. Want to do something after this asynchronous event is completed? You can append the callback to it, no matter how many ones are attached!

JQuery's Ajax method returns a Promise object (this is a key feature added by jQuery1.5 ). If I have two functions, do1 () and do2 (), to execute them after the asynchronous event is successfully completed, just do the following:

promise.done(do1);// Other code here.promise.done(do2);

This is much more free. I just need to save this Promise object and add any number of callbacks to it at any time of code writing, you don't have to worry about where the asynchronous event was initiated. This is the advantage of Promise.
Formal introduction

Promise is so useful to deal with asynchronous operations that it has evolved into A specification of CommonJS called Promises/. Promise indicates the return value after an operation is completed. It has three states:

  1. Yes (fulfilled or resolved), indicating that the Promise operation is successful.

  2. Negative (rejected or failed) indicates that the Promise operation failed.

  3. Wait (pending). No positive or negative results have been obtained.

In addition, there is also a nominal State to indicate that the Promise operation has been successful or failed, that is, a set of positive and negative States, called the end (settled ). Promise also has the following important features:

  • A Promise can only change from a waiting state to a positive or negative state once. Once it is changed to a positive or negative state, it will never change.

  • If a callback for success or failure is added after a Promise ends (successful or failed, as described earlier), the callback function is executed immediately.

Think about the Ajax operation. After initiating a request, wait, and then successfully receive the response or an error (failure ). Is this consistent with Promise?

Another good example of Promise's features is jQuery's $ (document). ready (onReady ). Here, the onReady callback function will be executed after the DOM is ready, but interestingly, if the DOM is ready before the code is executed, onReady will be executed immediately, there is no latency (that is, synchronous ).
Promise example
Generate Promise

Promises/A lists A series of JavaScript libraries that implement Promise. jQuery is also in it. The following code uses jQuery to generate Promise:

var deferred = $.Deferred();deferred.done(function(message){console.log("Done: " + message)});deferred.resolve("morin"); // Done: morin

JQuery specifically defines a class named Deferred, which is actually Promise. The $. Deferred () method returns a newly generated Promise instance. On the one hand, deferred is used. done (), deferred. fail () and so on. On the other hand, call deferred. resolve () or deferred. reject () to affirm or deny this Promise, and can transmit arbitrary data to the callback.
Merge Promise

Do you still remember the problem of sending two Ajax requests at the same time as I mentioned above? Taking jQuery as an example, Promise can solve it like this:

var promise1 = $.ajax(url1),promise2 = $.ajax(url2),promiseCombined = $.when(promise1, promise2);promiseCombined.done(onDone);

$. The when () method can combine multiple Promise to obtain a new Promise, which is equivalent to establishing the AND (logical AND) Relationship between the original multiple Promise. If all the Promise components are successful, the merged Promise is also successful. If any of the combined Promise fails, the merged Promise fails immediately.
Cascade Promise

Continue with the question of executing a series of asynchronous tasks in sequence in the previous article. It uses the most important Promise method. then () (in the Promises/A specification, it also defines Promise using the "object with then () method ). The Code is as follows:

var promise = $.ajax(url1);promise = promise.then(function(data){  return $.ajax(url2, data);});promise = promise.then(function(data){  return $.ajax(url3, data);});// ...

Promise. the complete form of the then () method is. then (onDone, onFail, onProgress). In this way, it looks like a simple method that can append all kinds of callbacks at a time (. done (),. fail ). Yes, you can use it like this, which is equivalent.

However, the. then () method also provides more useful functions. Like the meaning of then, it is used to clearly indicate the relationship between the asynchronous events: "first, then (then) then ". This is called the cascade of Promise.

To cascade Promise, note that in the callback function passed to then (), you must return the Promise that you want to represent the next task (such as the $. ajax (url2, data )). In this way, the variable assigned previously becomes a new Promise. If the callback function of then () does not return Promise, the then () method returns the original Promise.

Should it be hard to understand? From the perspective of code execution, the above Code with multiple then () is actually executed by the JavaScript engine once. But it is like writing a script for a dance drama. After reading it, the JavaScript engine will arrange actors to perform the script in sequence in the future, and the performances will be asynchronous. The then () method enables you to write asynchronous scripts.
Use Promise in callback-Based APIS

The $. ajax () method used repeatedly in the previous article will return a Promise object, which is actually only a special benefit provided by jQuery. In reality, most JavaScript APIs, including native functions in Node. js, are based on callback functions rather than Promise. In this case, you need to perform some processing on your own when using Promise.

This process is actually relatively simple and straightforward. The following is an example:

var deferred = $.Deferred();setTimeout(deferred.resolve, 1000);deferred.done(onDone);

In this way, the positive or negative trigger of Promise is passed in as the API callback, and the processing mode of Promise is changed.
How is Promise implemented?

This article writes Promise here, and you find that all of them are based on the existing libraries that implement Promise. So what if you want to build a Promise on your own?

Q, which is the first in the Promises/A database list, is the most intuitive and compliant with the Promises/A specification. If you want to know how to make a Promise, refer to the design pattern parsing provided by Q.

This article only describes the application of Promise. I will open an article in the future to detail the implementation details of Promise.

As a later version of JavaScript, ECMAScript 6 will provide Promise native. If you want to know its usage, it is recommended to read JavaScript Promises: There and back again.
Conclusion

The word Promise is so stubborn that it is not suitable for translation that it will not be meaningful at a glance. However, it can indeed provide a lot of help for complicated asynchronous tasks in JavaScript.

The above is how to use Promise in Asynchronous JavaScript programming _ node. js? 1.1.5. For more information, see the PHP Chinese website (www.php1.cn )!

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.