Introduction to the JavaScript Promises specification for asynchronous programming

Source: Internet
Author: User

What is Promises

Promises is a specification for asynchronous programming that standardizes asynchronous processing objects and processing rules and provides a unified interface for asynchronous programming.

The traditional callback function

When it comes to JavaScript's asynchronous programming, we usually think of callback functions, such as the following code:

Getfileasync ("1.txt", function (error, result) {if (error) {throw error; }//Processing on success});

  

The above code defines a function that gets the contents of the file, and calls the incoming callback function back after the read is completed, for the following scenario:

-Read the contents of the file 1.txt, the content is also a file address, we call 2.txt

-Read the contents of the file 2.txt, the content is also a file address, we call 3.txt

-Read the contents of file 3.txt

The code for using the callback function is as follows:

Getfileasync ("1.txt",  function (ERROR1, RESULT1) {     if (Error1) {           throw error1;     }      getfileasync (Result1, function (ERROR2, RESULT2) {               if (Error1) {                throw error1;           }          getfileasync (RESULT2,  function (ERROR3, RESULT3) {                console.log (RESULT3);           });  (    });});

  

This is called the callback pyramid, the callback function nesting is very deep, the code is very bad to see, and not easy to read. Promise is the solution to flatten asynchronous callbacks.

Promises Specification

PROMISES/A (Http://wiki.commonjs.org/wiki/Promises/A) is an asynchronous Pattern programming specification developed by COMMONJS organization that provides a solution for describing the concept of delay (or future) in a program. The main idea is to execute an asynchronous method without blocking the application and returning a Promise object.

The promises/a+ (https://promisesaplus.com/) specification is a supplement and modification to the PROMISES/A specification.

The Promise object has three states: initial state (pending), success (fulfilled), and failure (rejected), where pending is the initial state, fulfilled and rejected are end states. The state transition relationship is: pending->fulfilled,pending->rejected, Promise object is converted from pending to fulfilled or After rejected , the state of this promise object will no longer change, such as:

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/139239/201604/139239-20160419100221695-1600446431. PNG "style=" border:0px; "/>

Promise is an object that has the then method, then the interface is used to listen for different states of a promise.

Then (Fulfilledhandler, ErrorHandler, Progresshandler);

After adding Fulfilledhandler, ErrorHandler, and Progresshandler, the Promise object is formed. Fulfilledhandler is called when promise is loaded with data, ErrorHandler is called when promise fails, and Progresshandler is invoked when the progress event is triggered.

var promise = Getasyncpromise ("FileA.txt");p romise.then (function (Result) {//Get the file content successful processing}, function (Error) {//Get Processing when the contents of the file fail);

  


Promises
Chaining calls

The then method returns a new Promise object instead of the original promise object after the Fulfilledhandler or ErrorHandler callback is completed, so that the promise operation can form a chained call.

var promise = new Promise (function (Resolve) {resolve (100);}); Promise.then (function (value) {return value * *;}). Then (function (value) {return value * *;}). Then (function (value) {Console.log (value);//= + 100 * 2 * 2});

  

Promises Error Handling

The then () function receives two callback functions as arguments. The function that the second callback function fires when promise becomes rejected. Promise also provides a catch () function to handle the rejected state of promise. Look at the following code:

Promise.then (fucntion (Result) {Console.log (' Got data! ', relust);}). catch (function (error) {Console.log (' Error occurred! ', error);});

  

The above code is actually equivalent to:

Promise.then (function (Result) {Console.log (' Got data ', result),},function (Error) {Console.log (' Error occurred! ', (error);});

  


Browser support:

Promises is now part of the JavaScript standard, and almost all browsers have implemented the Promises API, and browser compatibility is as follows:

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/139239/201604/139239-20160419100253898-865739553. PNG "width=" 875 "height=" 430 "style=" border:0px; "/>

This article briefly introduces the basics of promises, hopefully we can better use promises and write code more easily.


This article is from the "Grape City Control Technology Team Blog" blog, be sure to keep this source http://powertoolsteam.blog.51cto.com/2369428/1765274

Introduction to the JavaScript Promises specification for asynchronous programming

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.