The meaning and basic usage of the Promise object

Source: Internet
Author: User
the meaning of 1.Promise

Promise is a solution to asynchronous programming that is more logical and powerful than traditional solutions (callback functions and events).

The so-called promise is simply a container that holds the result of an event (usually an asynchronous operation) that will end in a future. Syntactically, promise is an object from which you can get messages for asynchronous operations.

The Promise object has the following 2 features:
1. The state of the object is unaffected by the outside world. The Promise object represents an asynchronous operation with three states: Pending (in progress), resolved (completed), and rejected (failed). Only the result of an asynchronous operation can determine which state it is currently in, and no other operation will be able to change that state. This is also the origin of the name promise, its English meaning is "commitment", that other means can not be changed.
2. Once the state has changed, it will not change, and this result can be obtained at any time. There are only two possible changes in the state of the Promise object: from Pending to resolved, from pending to rejected. As long as these two things happen, the state will solidify, will not change, will always maintain this result. Even if the change has already occurred, you will immediately get the result of the Promise object field static callback function. This is quite different from the event, which is characterized by the consequence that if you miss it and then listen to it, you will not get the result.

With the Promise object, the asynchronous operation can be expressed in the process of synchronous operation, and the callback function of layer nesting is avoided. In addition, the Promise object provides a unified interface that makes it easier to control asynchronous operations. 2. Basic Usage

ES6 stipulates that the Promise object is a constructor that is used to generate promise instances

var promise = new Promise (function (resolve,reject) {
  //... some code
  if (/* Asynchronous operation succeeded *) {
    resolve (value);
  } else{
    reject (Error);
  }
);

The promise constructor takes a function as an argument, and the two parameters of the function are resolve and reject respectively. They are two functions, provided by JavaScript engines, not deployed by themselves.

The role of the resolve function, which changes the state of the promise object from incomplete to successful (that is, from pending to resolved), calls when the asynchronous operation succeeds, and passes the result of the asynchronous operation as a parameter;
The Reject function is invoked when an asynchronous operation fails, and the error reported by the asynchronous operation is passed as a parameter.

After the promise instance is generated, you can use the then method to make a callback function for the resolved state and the rejected state respectively:

Promise.then (function (value) {
  //sucess
},function (Error) {/
  /failure
});

The then method can accept 2 callback functions as arguments, and the second function is optional and not necessarily provided. Both functions accept values that are outgoing from the Promise object as arguments.

The following is a simple example of a Promise object:

Function Timeout (ms) {return
  to new Promise (resolve,reject) =>{
    settimeout (resolve,ms, ' done ');
  }

Timeout. Then ((value) =>{
  console.log (value);
});

In the code above, the timeout method returns a Promise instance that represents a result that occurs after an event. After the specified time (MS parameter), the state of the promise instance becomes resolved, triggering the callback function that the then method binds.

Promise will be executed immediately after the new

Let promise = new promise (function (resolve,rejeact) {
  console.log (' promise ');
  Resolve ();
});

Promise.then (function () {
  console.log (' resolved ');
});

Console.log (' Hi ');

Promise
//Hi
/Resolved

In the code above, Promise executes immediately after the new one, so the first output is "Promise", and then the callback function specified by the then method is executed before all the synchronization tasks in the current script are executed, so "resolved" the last output.

The following is an example of an asynchronous loading picture:

function Loadimageasync (URL) {return
  new Promise (function (resolve,reject) {
    var image = new Image ();
    Image.onload = function () {
      resolve (image);
    Image.onerror = function () {
      reject (new Error (' could not load image at ' + URL)};

    image.src = URL;
  });

Here is an example of an AJAX operation with a Promise object:

var Getjson = function (URL) {var promise = new Promise (function (resolve,reject) {var client
    = new XMLHttpRequest ();
    Client.open (' get ', url);
    Client.onreadystatechange = handler;
    Client.responsetype = ' json ';
    Client.setrequestheader (' Accept ', ' Application/json ');

    Client.send ();
      function handler () {if (this.readystate!== 4) {return;
      } if (This.status = =) {resolve (This.response);
      }else{Reject (New Error (This.statustext));

  }
    }
  });
return promise;

}; Getjson ('/posts.jons '). Then (function (JSON) {consoloe.log (JSON);},function (Error) {Console.log (' Error ');}); 

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.