Basic usage of Promise

According to ES6, Promise object is a constructor used to generate Promise instance

const promist = new Promise(function(resolve,reject){
    if(/*Asynchronous operation succeeded*/){
        resolve(value);
    }else{
        reject(error);
    }
})

The resolve function is used to change the state of the Promise object from incomplete to successful (i.e. from pending to resolved), call when the asynchronous operation is successful, and pass the result of the asynchronous operation as a parameter
The reject function is used to change the state of the project object from "incomplete" to "failed" (that is, from "pending" to "rejected"), call when the asynchronous operation fails, and pass the error reported by the asynchronous operation as a parameter.

After the project instance is generated, you can use the then method to specify the callback functions for the resolved state and rejected state respectively.

promise.then(function(value){
//success
},function(error){
//failure
});

Example:

function timeout(ms){
    return new Promise((resolve,reject)=>{
        setTimeout(resolve,ms,'done');
    });
}
timeout(100).then((value)=>{
    console.log(value);
});
let promise = new Promise(function(resolve,reject){
    console.log('Promise');
    resolve();
});
promise.then(function(){
    console.log('resolved');
});
console.log('Hi!');

//Promise
//Hi!
//resolved
//Load pictures asynchronously
function loadImageAsync(url){
    return new Promise(function(resolve,reject){
        const image = new Image();
        image.onload = function(){
            resolve(image);
        };
        image.onerror = function(){
            reject(new Error('error');
        };
        image.src = url;
    });
}

Here is an example of an Ajax operation implemented with Promise objects.

const getJSON = function(url) {
  const promise = new Promise(function(resolve, reject){
    const handler = function() {
      if (this.readyState !== 4) {
        return;
      }
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    };
    const client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept", "application/json");
    client.send();

  });

  return promise;
};

getJSON("/posts.json").then(function(json) {
  console.log('Contents: ' + json);
}, function(error) {
  console.error('Error', error);
});

In short, it is to encapsulate a method. The return value of this method is a project object. In this project object, logical operations are carried out. After judgment, the right result is returned with resolve (return data), and the right and wrong data are returned with reject (return data).

Call method:

XXX (parameter). then(function(data){},function(error) {})

Tags: JSON

Posted on Sun, 09 Feb 2020 14:18:42 -0500 by lutzlutz896