describe

Promise

Promise is a solution to asynchronous programming that makes more sense and is more powerful than traditional solutions — callback functions and events. It was first proposed and implemented by the community, and ES6 has written it into the language standard, unifying usage, and providing Promise objects natively. Simply put, it is a container that holds the result of some event (usually an asynchronous operation) that will end in the future. Syntactically, a Promise is an object from which to get messages for asynchronous operations. Promise provides a uniform API, and all kinds of asynchronous operations can be handled in the same way. A Promise object represents a value that is not necessarily known when the Promise is created. It allows you to associate the eventual success return value or failure cause of an asynchronous operation with the appropriate handler. This allows asynchronous methods to return values as synchronous methods do: instead of returning the final value immediately, asynchronous methods return a promise to give the value to the consumer at some point in the future. A Promise must be in one of the following states:

  • Pending: The initial state that has neither been granted nor rejected.
  • This is a big pity: this will be fulfilled successfully.
  • Rejected: Indicates that the operation fails.

Once the state changes, it never changes again, and you can get this result at any time. There are only two possibilities for the state of the Promise object to change from pending to depressing and from pending to Rejected. As long as these two things are happening the state is fixed, it’s not going to change, it’s going to stay the same and that’s called resolved. If the change has already occurred, you can add a callback to the Promise object and get the same result immediately. This is quite different from an Event, which has the characteristic that if you miss it and listen again, you will not get the result.

Ajax

AJAX is a technique for updating parts of a web page without having to reload the entire page. AJAX = Asynchronous JavaScript and XML. AJAX is not a new programming language, but a new way to use existing standards. The five steps of an Ajax request:

  1. Create an XMLHttpRequest asynchronous object
  2. Set the request mode and address
  3. Send a request
  4. Listening for state changes
  5. Receive returned data

Create an object

Promise

const promise = new Promise(function(resolve, reject) {
  // ... some code

  if (/* Asynchronous operation succeeded */){
    resolve(value);
  } else{ reject(error); }});Copy the code

Ajax

var client;
if (window.XMLHttpRequest){
	// code for IE7+, Firefox, Chrome, Opera, Safari
	client=new XMLHttpRequest();
}
else{
	// code for IE6, IE5
	client=new ActiveXObject("Microsoft.XMLHTTP");
}
client.open("POST".'url');
client.responseType = "json";
// Accept indicates the type of data that the sender (client) wants to receive
client.setRequestHeader("Accept"."application/json");
/ / the content-type on behalf of the sender (client) | server sends the data Type of the entity data, if you don't write this one
client.setRequestHeader("Content-Type"."application/json; charset=UTF-8");
client.send(JSON.stringify({username:'admin'.password:'123456'}));
// Store the function (or function name) that is called whenever the readyState property changes.
client.onreadystatechange = function(){
// readyState holds the state of XMLHttpRequest. It goes from 0 to 4.
// 0: The request is not initialized
// 1: The server connection is established
// 2: Request received
// 3: The request is being processed
// 4: Request completed and response ready
// status 200: "OK"
    if(this.readyState === 4&&this.status === 200) {console.log('success');
    }else{
        console.log('failure'); }};Copy the code

Promise+Ajax does a wrapper

The following is an add-on to jQ’s Ajax: this code needs to run in the browser console, and then the URL enters the IP and port of the requested URL otherwise it will cross domains, and most importantly it needs to be able to provide the interface locally

function request({url,method,data,timeout,success,fail}){
	let client;
	console.log(url,method,data)
	return new Promise((resolve,reject) = > {
		if (window.XMLHttpRequest){
			// code for IE7+, Firefox, Chrome, Opera, Safari
			client=new XMLHttpRequest();
		}
		else{
			// code for IE6, IE5
			client=new ActiveXObject("Microsoft.XMLHTTP");
		}
		client.open(method, url);
		client.responseType = "json";
		client.timeout = timeout;
		client.setRequestHeader("Content-type"."application/json; charset=UTF-8");
		client.setRequestHeader("Accept"."application/json");
		client.setRequestHeader("Access-Control-Allow-Origin"."*");
		client.send(JSON.stringify(data));
		client.onreadystatechange = function(){
			if(this.readyState ! = =4) {return;
			};
			if(this.status === 200) {I am, therefore, underpaid. I therefore pay therefore I am underpaid
				success.call(undefined.this.response)
                                // The second is an internal callback
                                success(this.response)
                                
			}else{
				fail.call(undefined.this.statusText) } }; })}; request({url:'http://127.0.0.1:3000/login/loginSubmit'.method:'post'.timeout:120000.data: {username:'admin'.password:'123456'
	},
	success: res= > {
		console.log(res)
	},
	fail: err= > {
		console.log(err)
	}
});
Copy the code

Promise basic usage

After the Promise instance is generated, you can use the THEN method to specify the resolved and Rejected state callback functions, respectively.

// bad
promise
  .then(function(data) {
    // success
  }, function(err) {
    // error
  });

// good
promise
  .then(function(data) { //cb
    // success
  })
  .catch(function(err) {
    // error
  });
Copy the code

The then method can take two callback functions as arguments. The first callback is called when the Promise object’s state changes to Resolved. The second callback is called when the Promise object’s state changes to Rejected. Both of these functions are optional and do not have to be provided. They all accept the value passed out from the Promise object as an argument. In the above code, the second method is better than the first because it catches errors in the execution of the previous then method and is closer to the synchronous method (try/catch). Therefore, it is recommended to always use the catch() method instead of the second argument to the then() method. Promises are implemented as soon as they are created.

let promise = new Promise(function(resolve, reject) {
  console.log('Promise');
  resolve();
});

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

console.log('Hi! ');

// Promise
// Hi!
// resolved
Copy the code

Promise.prototype.finally()

The finally() method is used to specify actions that will be performed regardless of the final state of the Promise object.

 promise
.then(result= >{...}). The catch (error= >{...}). Finally,() = > {···});
Copy the code

Promise.all()

The promise.all () method is used to wrap multiple Promise instances into a new Promise instance.

const p = Promise.all([p1, p2, p3]);
Copy the code

In the code above, the promise.all () method takes an array of arguments. P1, p2, and p3 are all Promise instances. If they are not, the Promise. In addition, the promise.all () method can take arguments that are not arrays, but must have an Iterator interface and return each member as a Promise instance.

The state of P is determined by P1, P2 and P3, which can be divided into two cases.

(1) Only when the states of P1, P2 and P3 become depressing, the state of P will become depressing. At this time, the return values of P1, P2 and P3 will form an array and be passed to the callback function of P.

(2) As long as p1, P2 and P3 are rejected, P becomes rejected, and the return value of the first rejected instance is passed to p’s callback function.

Promise.race()

The promise.race () method again wraps multiple Promise instances into a new Promise instance.

const p = Promise.race([p1, p2, p3]);
Copy the code

In the above code, the state of P changes as long as one of the first instances of P1, P2, and P3 changes state. The return value of the first changed Promise instance is passed to p’s callback.

Promise.allSettled()

The promise.allSettled () method takes a set of Promise instances as parameters and wraps them into a new Promise instance. The wrapper instance will not complete until all of these parameter instances return the result, whether this is fulfilled or Rejected. This method returns a new Promise instance. Once it is fulfilled, the state is always fulfilled and will not become Rejected. After the state becomes depressing, the Promise listener receives an array of parameters, each member corresponding to an incoming promise.allSettled () Promise instance.

const resolved = Promise.resolve(42);
const rejected = Promise.reject(-1);

const allSettledPromise = Promise.allSettled([resolved, rejected]);

allSettledPromise.then(function (results) {
  console.log(results);
});
/ / /
// { status: 'fulfilled', value: 42 },
// { status: 'rejected', reason: -1 }
// ]
Copy the code

Sometimes we don’t care about the results of asynchronous operations, only whether they end or not. In this case, the promise.allSettled () method is useful.

Promise.any()

Promise. Any () method. The method takes a set of Promise instances as parameters and returns them wrapped as a new Promise instance. As long as one parameter instance becomes a depressing state, the packaging instance will become a depressing state. If all parameter instances become the Rejected state, the wrapper instance becomes the Rejected state. The error thrown by promise.any () is not a generic error but an AggregateError instance. It is equivalent to an array, with each member corresponding to an error thrown by the Rejected operation. Here is an example implementation of AggregateError.

var resolved = Promise.resolve(42);
var rejected = Promise.reject(-1);
var alsoRejected = Promise.reject(Infinity);

Promise.any([resolved, rejected, alsoRejected]).then(function (result) {
  console.log(result); / / 42
});

Promise.any([rejected, alsoRejected]).catch(function (results) {
  console.log(results); // [-1, Infinity]
});
Copy the code

Promise.resolve()

Sometimes you need to turn an existing object into a Promise object, and the promise.resolve () method does this.

Promise.resolve('foo')
/ / equivalent to the
new Promise(resolve= > resolve('foo'))
Copy the code

The arguments to the promise.resolve () method are divided into four cases.

1. The parameter is onePromiseThe instance

If the argument is a Promise instance, promise.resolve will return the instance unchanged.

2. The parameter is onethenableobject

Thenable objects refer to objects that have then methods, such as this one.

let thenable = {
  then: function(resolve, reject) {
    resolve(42); }};Copy the code

The promise.resolve () method turns this object into a Promise object and immediately executes the thenable object’s then() method.

let thenable = {
  then: function(resolve, reject) {
    resolve(42); }};let p1 = Promise.resolve(thenable);
p1.then(function (value) {
  console.log(value);  / / 42
});
Copy the code

3. The parameter does not existthen()Method object, or not object at all

If the parameter is a raw value, or an object that does not have a then() method, the promise.resolve () method returns a new Promise object with the state Resolved.

const p = Promise.resolve('Hello');
p.then(function (s) {
  console.log(s)
});
// Hello
Copy the code

The code above generates a new instance P of the Promise object. Since the string Hello is not an asynchronous operation (the string object does not have the then method), the return Promise instance state from lifetime achievement is Resolved, so the callback will execute immediately. The arguments to the promise.resolve () method are also passed to the callback function.

4. No parameters

The promise.resolve () method allows a call with no arguments to return a Resolved Promise object. So, if you want a Promise object, the convenient way to do this is to call the promise.resolve () method directly. Note that the Promise object for resolve() now is executed at the end of this event loop, not at the beginning of the next.

setTimeout(function () {
  console.log('three');
}, 0);

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

console.log('one');

// one
// two
// three
Copy the code

Promise.reject()

The promise.Reject (Reason) method also returns a new Promise instance with a state of Rejected.

const p = Promise.reject('Wrong');
/ / is equivalent to
const p = new Promise((resolve, reject) = > reject('Wrong'))

p.then(null.function (s) {
  console.log(s)
});
/ / make a mistake
Copy the code

Promise.try()

Promise.try() simulates a try block, just as promise.catch simulates a catch block. However, it does not affect synchronous asynchrony, which is still carried out synchronously, and asynchronous which is carried out asynchronously.

Promise.try(() = > database.users.get({id: userId}))
  .then(...)
  .catch(...)
Copy the code

For more information about PROMISE, click Ruan Yifeng – ES6 Starter – Promise

see

1. Ruan Yifeng – Introduction to ES6
2. Javascript|MDN
3. W3school
4. blibli-KuiSAhn
5. Blogosphere. – Look at that