Talking about the use of the Promise of ES6

Promise foundation

The official document:

api/new-promise.html

A good principle to explain the article:

Understanding and use of Promise, refactor your code for Js

Promise is to address the emergence of callback hell. Nested loops to reduce the code and instead write code similar to the series.

Today most of the browsers support the Promise. We can look at the output in the console.

Here Insert Picture Description

We can see Promise()a capital P Description This is a constructor. We need to pass with resolveand rejectfunction
while prototypewe can see in thenand catchthese two functions. These two functions is the key to solving the callback hell.
Principle of knowledge, venue and I can give the link. below primarily in connection with the use of the code to talk about.

Use Promise

Promise constructor

Promise processing operation is asynchronous, and the execution order to execute the main program is JS, after the asynchronous operation
For ease of demonstration, used setTimeout()to simulate the asynchronous request

Look at the following code

new Promise((resolve, rejcet) => {
	setTimeout(() => {
		console.log('Promise')
	}, 2000)
	console.log('in Promise')
});

console.log('out Promise')

Output

in Promise
out Promise
Promise

So, we can know when the new Promise, which code will be executed immediately.

So how did our code to execute Promise in action at the right time you want it?

We can write the new Promise to a function, and then call when needed, for example, the following code:

function testPromise() {
	return new Promise((resolve, rejcet) => {
		setTimeout(() => {
			console.log('Promise')
		}, 2000)
		console.log('in Promise')
	});
}
console.log('out Promise')
testPromise()

Output

out Promise
in Promise
Promise

Constructor function

new Promise((resolve, rejcet) => {... }You can see the new Promise was introduced to function with two parameters when.
Which resolveis when the asynchronous method is successful, and rejectis called when the failures

The following code, I wrote a timer and combined ajax()to simulate an asynchronous request, where the first parameter flagis used to simulate is abnormal,
we can step back to look, it will be mentioned below its execution order

// 模拟ajax请求 第一个参数来模拟是否出现异常
function ajax(flag, err, data, resolve, reject) {
	// return 并不会起到返回的作用,只是为了代码到此结束
	if (flag == false)
		return reject(err)
	resolve(data)
}

function testPromise(err, data, flag) {
	return new Promise((resolve, reject) => {
		// 设置ajax(ture/false,...)来决定是否有异常
		setTimeout(ajax(flag, err, data, resolve, reject), 2000)
	})
}

testPromise('出错了 err', '没有错误,返回数据data', true)
	.then((data) => {
		console.log('----回调resolve :' + data)
	})
	.catch(err => {
		console.log('----回调reject :' + err)
	})

Execution order

The code above, at first glance it is a mess, some logical confusion following comb the order of execution

  • testPromise ( 'wrong err', 'no error, the data returned data') This line of code callstestPromise(err, data)
  • Previous step new Promise ((resolve, reject) => {}) in resolveand rejectdo not have any value and returns immediately a Promisesubject
    • At this time, the object returns a Promise, however resolve, and rejectstill no specific function, but functions are placeholders. Will be later injection
    • And setTimeout (ajax (false, err, data, resolve, reject), 2000) is a second timer delay, JS et 2s then executes it (asynchronous analog)
  • Next Back .then (data => {...} ) then()will pass a particular function to be performed after the success of the asynchronous method. That is injected resolve, and .catch (err => {}) will be injectedreject
  • At this resolve, reject all have a specific function, the above steps are to be completed extremely fast in JS
  • After 2s, the implementation of the setTimeout ()
  • Ajax () of the flag == false then performs a return reject (err) to the callback .catch (err => {})
  • Output console.log ( '---- callback reject:' + err)

Request Asynchronous not return a return value

Specific use

Through the above code and explanation, we have seen special Promise, but how can we solve specific callback hell of it?

testPromise('出错了 err', '没有错误,返回数据data', true)
	.then((data) => {
		console.log('----回调resolve :' + data)
		return testPromise('哈哈哈,又错了', '这一次还没有错', true)
	})
	.then(data => {
		console.log('----回调resolve :' + data)
	})
	.catch(err => {
		console.log('----回调reject :' + err)
	})

Output

----回调resolve :没有错误,返回数据data
---回调resolve :这一次还没有错

It must also return an Promiseinstance before they can be used again .then()method

In this way, we can see the original nested code, we have passed the .then()series to together.
A call to return as long as the Promiseinstance, you can infinitely .then()down

Exception handling

The above code is by catch()abnormal capture.

function testPromise(err, data) {
	return new Promise((resolve, reject) => {
		// 设置ajax(ture/false,...)来决定是否有异常
		setTimeout(ajax(false, err, data, resolve, reject), 2000)
	})
}

testPromise('出错了 err', '没有错误,返回数据data')
	.then((data) => {
		console.log('----回调resolve :' + data)
		return testPromise('哈哈哈,又错了', '这一次还没有错')
	})
	.then(data=>{
		console.log('----回调resolve :' + data)
	})
	.catch(err => {
		console.log('----回调reject :' + err)
	})

Output:

----回调reject :出错了 err

The result is output only once wrong
we can know the result catch()is an unusually long as the code, after the emergence of Promise execution chain will not be executed

So how do we make Promise execution chain if the latter exception code error that still enforce it?

in fact.then(function(){},function(){} )

.then()Both functions can be passed

  • A handler for the first function is normally performed must pass
  • The second function is to handle exceptions, can not wear. If passed, .catch will not be processed, so as not to affect the execution chain Promise
  • Both of these functions need to return an Promiseinstance in order to continue execution chain
testPromise('出错了 err', '没有错误,返回数据data', false)
	.then((data) => {
		console.log('----回调resolve :' + data)
		return testPromise('哈哈哈,又错了', '这一次还没有错', false)
	},err =>{
		console.log(err)
		return testPromise('哈哈哈,又错了', '这一次还没有错', false)
	})
	.then(data => {
		console.log('----回调resolve :' + data)
	})
	.catch(err => {
		console.log('----回调reject :' + err)
	})

Output

出错了 err
----回调reject :哈哈哈,又错了

axios

axios is based on a promise of HTTP library
which had a very good package, especially some common get, post requests. And also a very good blocker mechanism
is also recommended, especially the power of God, so we can find out.

axios Chinese Description

Published 92 original articles · won praise 18 · views 60000 +

Guess you like

Origin blog.csdn.net/qq_34120430/article/details/89416199