A Promise,

1. Three states

pending resolved rejected

2. Performance and change of state

State of expression:

Pending state, which does not trigger then and catch

Resolved state, which triggers subsequent THEN callbacks

The Rejected state triggers the subsequent catch callback

Switch status: Resolved => Resolved or Pending => Rejected

3. Influence of THEN and catch on state

Resolved then Return Rejected when the error message is returned

‘Catch’ returns’ Resolved ‘and’ Rejected ‘when an error is reported

4. Chain calls to then and catch

	/ / 1
	Promise.resolve().then(() = > {
		console.log(1)  //1, return as normal, trigger resolved, and proceed with the subsequent then function
	}).catch(() = > {
		console.log(2)
	}).then(() = > {
		console.log(3) / / 3, resolved
	})

	/ / the second question
	Promise.resolve().then(() = > {
		console.log(1)
		throw  new Error('error1')  //1 (rejected); //1 (rejected)
	}).catch(() = > {
		console.log(2) //2, no error, trigger resolved, execute then
	}).then(() = > {
		console.log(3) / / 3, resolved
	}) / / 1 2 3

	/ / the third topic
	Promise.resolve().then(() = > {  // Rejected triggers the catch callback
	    console.log(1)   / / 1
	    throw new Error('erro1')
	}).catch(() = > {     // Resolved to trigger then callback
	    console.log(2)   / / 2
	}).catch(() = > { // Catch
	    console.log(3)})Copy the code

Second, the async/await

  • Asynchronous callback callback hell

  • Promise then catch chain calls, but also based on callback functions

  • Async /await is synchronous syntax and eliminates callback functions completely

  • Async /await is the ultimate weapon against asynchronous callbacks, and promises are not exclusive, but complement each other

1. Relationship between async/await and Promise

  • Async functions return Promise objects (if no Promise is returned in the function, it will be wrapped automatically)
  • The async function is executed and returns a Promise object
	async function fn1(){
		return 100  // return promise.resolve (100)
	}

	const res1 = fn1()
	console.log('res1',res1)  Async returns a promise function
	res1.then(data= >{
		console.log('data',data)  / / 100
	})

Copy the code
  • ‘await’ is equivalent to ‘then’ of primise
! (async function(){
		const p1 = Promise.resolve(300)
		const data = await p1 //await equals Promise then
		console.log('data',data) })() ! (async function(){
		const data1 = await 400 //await Promise.resolve(400)
		console.log('data1',data1) })() ! (async function(){
		const data2 = await fn1() //await Promise.resolve(400)
		console.log('data2',data2)
	})()

Copy the code
  • try… Catch catches exceptions instead of the catch of promise
! (async function(){
		const p4 = Promise.reject('err1')  / / rejected state
		try {
			const res = await p4
			console.log(res)
		} catch(e) {
			console.log(e); //try... Catch is equivalent to a promise catch
		}
	})()
Copy the code

Note:

! (async function(){
		const p5 = Promise.reject('err1')  / / rejected state
		const res = await p5 // await then, rejected
		console.log('res',res)
	})()
Copy the code

To sum up:

  • Async encapsulation Promise
  • Await processing Promise success
  • try… The catch processing Promise failed

4. Asynchronous nature

Await is synchronous, but it is still an asynchronous call in nature.

async function async1 () {
  console.log('async1 start')  / / 2
  await async2()   
  console.log('async1 end') //5, this is the key step, it is equivalent to the callback, the last execution
}

async function async2 () {
  console.log('async2')   / / 3
}

console.log('script start')  / / 1
async1()
console.log('script end')   //4, the synchronization is complete, and the asynchrony starts
Copy the code

That is, whenever an await is encountered, the following code is equivalent to being placed in a callback.

async function async1 () {
  console.log('async1 start')  / / 2
  await async2()   
  // The following three lines are the contents of the asynchronous callback
  console.log('async1 end')  / / 5
  await async3()  
  // The next step is for the asynchronous callback
  console.log('async 1 and 2') / / 7
}

async function async2 () {
  console.log('async2')   / / 3
}

async function async3 () {
  console.log('async3')   / / 6
}


console.log('script start')  / / 1
async1()
console.log('script end')   //4, the synchronization is complete, and the asynchrony starts
Copy the code

Fifth, the for… of

// Time the multiplication
function multi(num) {
    return new Promise((resolve) = > {
        setTimeout(() = > {
            resolve(num * num)
        }, 1000)})}// // uses forEach, which prints all results after 1s, i.e., the three values are computed together
// function test1 () {
// const nums = [1, 2, 3];
// nums.forEach(async x => {
// const res = await multi(x);
// console.log(res);
/ /})
// }
// test1();

/ / used for... "Of" allows calculations to be executed sequentially
async function test2 () {
    const nums = [1.2.3];
    for (let x of nums) {
        / / in the for... Inside the body of the "of" loop, await is evaluated sequentially
        const res = await multi(x)
        console.log(res)
    }
}
test2()
Copy the code

Reference: blog.csdn.net/qdq2014/art…