Asynchronous JavaScript objects ES6 Promise

Brief introduction

Promise objects: represent some future event (usually an asynchronous operation) will take place.
It simply is a container, which holds the event will end sometime in the future (usually an asynchronous operation) results. Syntactically, Promise is an object, you can get messages from the asynchronous operation of it.
Promise of an object ES6, asynchronous operation can be expressed in a synchronized process, a good solution to the problem of callback hell.

Callback Hell: a nested callback function callback or other phenomena of high coupling. If there is an error callback hell will affect many other parts, and difficult to maintain and secondary development.

Three states promise object

  • Initialization state (wait state): pending
  • Success status: fullfilled
  • Failed states: rejected

The basic steps of promise

  1. Create a promise Objects
  2. Calls promise callback function then ()

Promise object has the following two characteristics.

  1. State of the object without outside influence. Three states: pending (in progress), fulfilled (been successful) and rejected (failed). Only results of asynchronous operations, you can decide what kind of current state, no other operations can change that state. Promise This is the origin of the name, which in English means "commitment", he said other means can not be changed.
  2. Once the status change, it will not change any time can get this result . Promise object changes state, only two possibilities: from pending from pending changes to become fulfilled and rejected. As long as these two things happens on the solidification state, it will not be changed and will keep the result, then called resolved (finalized).

grammar

Creating a promise object syntax is as follows:

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

  if (/* 异步操作成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});
  • Promise constructor takes a function as a parameter, two parameters are the function resolve and reject. They are two functions provided by the JavaScript engine, you do not have to deploy.
  • Function is to resolve the role of the state of the object from Promise "unfinished" to "success" (i.e., changed from pending resolved), upon successful call asynchronous operation, and the result of the asynchronous operation, to pass out as a parameter;
  • Function is to reject the role of the state of the object from Promise "unfinished" to "failed" (i.e., changed from pending Rejected), invoked when an asynchronous operation fails, and the asynchronous operation errors may be, as a parameter to pass out .

.then

After generating Promise example, you can specify a callback function resolved state by state and then rejected Methods.

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

For chestnuts

The following parameters can be seen that the code is a promise arrow constructor function, a function of two parameters arrow resolve, reject. This time the arrow into the function state "the Pending"
IF statement to determine the status of implementation of asynchronous operations:

  • If successful implementation resolve (), promise the status is automatically changed to fullfilled.
  • If it fails to execute reject (), promise the status is automatically changed to rejected.

The results of the if statement, which is executed resolve () or reject (), regardless of which one can give promise.then () to pass parameters. promise.then(function(value) { // success}, function(error) { // failure });If successful, promise.then will perform the method parameters 1, if it fails, it will execute the method parameter 2.
Here Insert Picture Description
The code above outputs: Here Insert Picture Description
I wrote the promise is if(true)so performs resolve(), then .thenit will execute the first argument of the method, which is the output of "success."

Create success or failure of the object Promise

That is, if you only need to deal with the successful outcome of treatment failure or just the result, it can be abbreviated. Below are equivalent wording.
Here Insert Picture Description
Errors may be captured then by the second argument of the method can also be used to capture the error catch. Versions are equivalent.
Here Insert Picture Description
Supplementary :

promise
.then(result => {···})		//两个参数方法,前面正确后面错误
.catch(error => {···})		//一个参数方法,只处理错误
.finally(() => {···});		//一个参数方法,正确错误都可以处理,ES2018出现

promise和AJAX

We normally 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) {
						//处理成功请求
					} else {
						//处理失败请求
					}
				}
			}
			pro.send();

That promise and how it combined with ajax. As long as the code parameter method promise to move in to. You can then be treated with an if statement resolve () and reject ().
Here Insert Picture Description
Of course, promise of parameters can be normal function, the function can also write arrow

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

For chestnuts

Examples can be seen in the success of my request. The if statement entered resolve (pro), then the parameters passed then, then the implementation of the resolve, to output the result of my request.
Here Insert Picture Description

native method fetch ajax

The code below is what I put on top of the screenshot can improve the look, encapsulate the promise of it, and then returned with the contents JSON.parse()into a string of JavaScript.

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

//封装起来
		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);
			})
		}
//调用
		var ajaxPro = promise(myUrl);
		
		ajaxPro.then(function(result) {
			var res = JSON.parse(result.responseText);
			console.log(res);		//输出 {name: "promisezzz", demo: "hahahahdemo"}
		}, function(err) {});

On top of this code is to help understand the promise of it, the actual writing of the ajax method with fetch just fine. 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"}
			})
		})
Published 131 original articles · won praise 451 · views 540 000 +

Guess you like

Origin blog.csdn.net/qq_36667170/article/details/105053979