Understanding JavaScript Promises

Source: Internet
Author: User

JavaScript has many slots, and nested callback may be referred to by thousands of people. A long time ago, I used async to handle nested callbacks in JavaScript asynchronous programming. Of course, I have also probably learned some other class libraries designed to solve these problems, such as EventProxy, Jscex, StepJS, and thenjs. When I first saw the Promises specification, I couldn't understand the benefits it brought. For example, each person who first learns Promises has seen the following sample code: // callbacks function callback (err, value) {<br> if (err) {<br> // do something <br> return; <br >}< br> // do other things with value} // Promises promise. then (function (value) {<br> // do something with value}, function (err) {<br> // do other things with error }) it is hard to believe that the above Code will make people look at Promises. However, as Petka, author of bluebird, said, the above code is "the most dishonest comparison ". So I urge you to erase similar code from your memory. Let's go back to the async discussion. The problem with async is that it cannot respond elegantly to changes in requirements. Once the business logic changes significantly, the code structure will be greatly adjusted, while Promises can easily cope with such changes. When the time is right, I will make a detailed comparison. First, let's get to know Promises quickly. Promises represents the final result of an asynchronous operation. Promises interaction mainly uses the then method. The then method accepts a callback function. This callback function accepts the returned values of successful execution or the Error cause of execution failure. The Error is generally caused by the Error object. Note that the return value of the then method execution is a Promise object, while the return value of the callback function accepted by the then method can be any JavaScript Object, including Promises. Based on this mechanism, the chained call of the Promise object takes effect. The Promises state Promise object has three states: pending (initial state), fulfilled (successful execution), and rejected (execution error ). The pending state's Promise object can be converted to the other two States. The text above is not good enough. You may wish to use some code to deepen your understanding of Promises. Note: Due to the unsatisfactory implementation of Promises/A + standards in mainstream JavaScript environments (including NodeJS), I used A third-party class library bluebird in my example. Var fs = require ('fs') var Promise = require ('bluebird') // modify fs. readFile is the Promise version var readFileAsync = function (path) {// return a Promise object, initial state pending return new Promise (function (fulfill, reject) {fs. readFile (path, 'utf8', function (err, content) {// The pending status changes to the rejected status if (err) return reject (err) // The pending status changes to fulfilled status return fulfill (content)} // call its then method, and the callback accepts the returned value readFileAsync ('. /pro Mise-1.js '). then (function (content) {console. log (content)}) after reading the above Code, Do you think Promises is actually not complex. OK. Let's continue with the above Code to make a simple comparison of the differences in the use of traditional callbacks and Promises:/** simple comparison of the requirements of the traditional approach and Promises approach: read two files and print the content ** // callbacks fs. readFile ('. /promise-1.js ', 'utf8', function (err, content1) {// nest a console. log ('#', content1) fs. readFile ('. /promise-1.js ', 'utf8', function (err, content2) {// second nested console. log ('##', content2)}) // Promises readFileAsync ('. /promise-1.js '). then (function (content1) {console. log ('#', content1 )/ /Return a Promise object return readFileAsync ('. /promiscuitye-1.js ')}). then (function (content2) {console. log ('#', content2)}) the above Code does not handle errors, which is a bad habit with serious consequences. However, the focus of today is not here, but to analyze the main differences between the two sections of code. The first piece of code is a traditional nested callback, which has been indented twice during the second printing, and the Promises chained call of the then method successfully avoids one indentation (nesting ), the code structure is relatively flat. The above code is a little simple. If you add error processing, Promises will undoubtedly shine. If you are interested, please follow the subsequent chapters. This chapter is over. I believe you have a preliminary understanding of Promises. Normative documents are often hard to understand. I do not describe too many normative documents, because I believe that the code can best explain everything. However, if you are interested in the standard documentation, you can read the reference link on your own.

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.