Javascript Promises Introduction

Source: Internet
Author: User

What is promisespromises is a specification for asynchronous programming that standardizes asynchronous processing objects and processing rules and provides a unified interface for asynchronous programming. Traditional callback functions talk about the asynchronous programming of JavaScript, and usually we think of callback functions, such as the following code:
function (Error, result) {     if(error) {         throw  error;     }     // processing when success is achieved );

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 file 2.txt content, its content or a file address, we call 3.txt-read the contents of the file 3.txtthe 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. The Promises specification promises/a (Http://wiki.commonjs.org/wiki/Promises/A) is an asynchronous Pattern programming specification developed by the COMMONJS organization, Provides a solution that describes 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. 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 from PendingConverted to fulfilledOr rejectedAfter that, the state of the Promise object will no longer change, such as: Promise is an object with the then method, then the interface is used to listen to a promise of different states.
   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 contents of the file successfully processed}, function (Error) {     //Get processing when file content fails});

Promises chaining 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 chain call.
var promise = new Promise (function (resolve) {    resolve ();});  Promise.then (function (value) {     return value * *;}). Then (function (value) {     return value * *;}). Then (function (value) {     console.log (value);//= + 100 * 2 * 2});

The Promises error handling 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, almost all browsers have implemented the Promises API, browser compatibility is as follows: This article briefly introduces the basic knowledge of Promises, Hopefully we can better use promises and write code more easily.

Javascript Promises Introduction

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.