This is the 11th day of my participation in the August More Text Challenge

Introduction to the

Promise object: represents some future event (usually an asynchronous operation) that will occur.

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.

The Promise object in ES6 solves the problem of callback hell by expressing asynchronous operations in a synchronous flow.

Callback hell: The phenomenon of nested layers of callback functions or high coupling of other callback functions. A callback hell where one error affects a lot of other parts and is difficult to maintain and redevelop.

The three states of the promise object

  • Initialization state (waiting state) : Pending
  • Success status: Fullfilled
  • Failed status: Rejected

Basic steps for using Promises

  1. Create a Promise object
  2. Call promise’s callback function then()

Promise objects have two characteristics.

  1. The status of an object is not affected. This is a big pity. There are three states: pending, fulfilled and rejected. Only the result of an asynchronous operation can determine the current state, and no other operation can change the state. That’s where the name “Promise” comes from. Its English name means “Promise,” indicating that nothing else can change it.

  2. 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.

grammar

The syntax for creating a Promise object is as follows:

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

  if (/* Asynchronous operation succeeded */){
    resolve(value);
  } else{ reject(error); }});Copy the code
  • The Promise constructor takes a function as an argument, resolve and reject. They are two functions that are provided by the JavaScript engine and do not need to be deployed themselves.
  • The resolve function changes the state of the Promise object from “unfinished” to “successful.” It will be called when the asynchronous operation succeeds and will pass the result of the asynchronous operation as an argument.
  • The Reject function changes the state of the Promise object from “unfinished” to “failed” (i.e., from Pending to Rejected). It is called when the asynchronous operation fails and passes the error reported by the asynchronous operation as a parameter.

.then

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

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

Take a chestnut

The promise constructor takes an arrow function that takes resolve, reject. Enter the arrow function with a pending if statement to determine the status of the asynchronous operation:

  • If resolve() is executed successfully, the promise state is automatically changed to fullfilled.
  • If you reject() fails, the promise state is automatically changed to Rejected.

The result of the if statement, resolve() or reject(), can pass arguments to promise.then(). promise.then(function(value) { // success}, function(error) { // failure }); If it succeeds, promise.then executes the method of parameter 1, and if it fails, the method of parameter 2.

The above code outputs:

I said if(true) in the promise, which will execute resolve(), and then.then will execute the method of the first argument, which will say “success.”

Create successful or failed Promise objects

That is, if you only want to deal with success results or only want to deal with failure results, that’s fine. All of these things are equivalent.

Errors can be caught using the second argument method of then, or they can be caught using catch. They’re all equivalent.

supplement:

promise
.then(result= > {···})		// Two parameter methods, the first is correct and the second is wrong
.catch(error= > {···})		// a parameter method that handles only errors
.finally(() = > {···});		// a parameter method can handle both correct and wrong, ES2018 appears
Copy the code

Promise and AJAX

Normally we write Ajax like this:

			var pro = new XMLHttpRequest;
			pro.open(method, url);
			pro.onreadystatechange = function() {
				if (pro.readyState == 4) {
					if (pro.status == 200 || pro.status == 304) {
						// The request was successfully processed
					} else {
						// Process failed requests
					}
				}
			}
			pro.send();
Copy the code

So how does promise combine with Ajax? Just move this code into the Promise’s parameter method. The if statement can then be processed with resolve() and reject().

Of course, the promise argument can be a normal function, as can the arrow function

		var ajaxPro = new Promise((resolve, reject) = > {})
		var ajaxPro = new Promise(function(resolve, reject) {})
Copy the code

Take a chestnut

In the example, you can see that my request was successful. The if statement enters resolve(pro) and passes the argument to then, which executes resolve and prints the result I requested.

Fetch, ajax’s native method

Parse () converts the return content to a JavaScript string using json.parse ().

		let myUrl = "ajax/13promise.json";

// Encapsulate
		function promise(url) {
			return new Promise(function(resolve, reject) {
				var pro = new XMLHttpRequest;
				pro.open("GET", url);
				pro.onreadystatechange = function() {
					if (pro.readyState == 4) {
						if (pro.status == 200 || pro.status == 304) {
							resolve(pro);
						} else {
							reject(pro);
						}
					}
				}
				pro.send(null); })}/ / call
		var ajaxPro = promise(myUrl);
		
		ajaxPro.then(function(result) {
			var res = JSON.parse(result.responseText);
			console.log(res);		{name: "promisezzz", demo: "hahahahdemo"}
		}, function(err) {});
Copy the code

The above code is just to help you understand the promise, use ajax fetch when you actually write it. The fetch method is given below:

		let myUrl = "ajax/13promise.json";
		fetch(myUrl).then(function(result){
			var res = result.json();
			res.then(function(response){
				console.log(response);		{name: "promisezzz", demo: "hahahahdemo"}})})Copy the code