ES6: Detailed explanation of Promise

1. Concept

Promise is a new solution for asynchronous programming in JS, which is more reasonable and powerful than callback functions and events.
Syntactically speaking: Promise is a constructor
Functionally speaking: Promise objects are used to encapsulate an asynchronous operation and can obtain the result value of its success/failure

2. Promise has 3 states

  1. Pending: The initial state is also called the waiting state
  2. resolved: success status
  3. rejected: failed status

Once the state is changed, it cannot be changed again. Once a promise instance is created, it is executed immediately.

3. The difference between Promise and async and await

What is async/await?
async/await is the ultimate solution to asynchrony based on Promise proposed by ES7.
Differences:
1. promise is ES6, async/await is ES7.
2. async/await is more elegant than promise.
3. Reject status:
1) Promise errors can be caught by catch, and it is recommended to catch errors at the end.
2) async/await is both You can use .then and try-catch to capture
a function. If you add async, then the function will return a Promise.
Async and await can be said to be the ultimate asynchronous solution. Compared with using Promise directly, the advantage lies in the processing of then The call chain can write the code more clearly and accurately. After all, writing a lot of then is also disgusting, and it can also solve the problem of callback hell elegantly. Of course, there are also some disadvantages, because await
transforms asynchronous code into synchronous code. If multiple asynchronous codes have no dependencies but use await, performance will be reduced.

4、Promise API

  1. Promise.resolve(value) class method, this method returns a Promise object resolved with the value value
  • If the value is a thenable (that is, with a then method), the returned Promise object will "follow" the thenable object and adopt its final state (resolved/rejected/pending/settled)
  • If the value passed in is itself a Promise object, the object is returned as the return value of the Promise.resolve method.
  • In other cases, return a Promise object with this value as success status.
  1. Promise.reject class method, and the only difference from resolve is that the state of the returned promise object is rejected.
  2. Promise.prototype.then gets the correct result of an async task
  3. Promise.prototype.catch get exception information
  4. Promise.prototype.finally will be executed on success or failure
  5. Promise.all() accepts an array of Promise objects as a parameter, and its return parameter is also an array. When all promises are resolved, it will enter the .then() method. As long as one promise is rejected, it will enter .catch() to process multiple asynchronous tasks concurrently. Only when all tasks are executed can the result be obtained.
  6. The parameters accepted by Promise.race() are the same as those of Promise.all(). The difference is that it will identify the promise object that reaches resolve or reject the fastest. If it is the fastest resolve, it will enter the .then() method. If it is reject, enter the .catch() method to process multiple asynchronous tasks concurrently, and the result can be obtained as long as one task is completed.

5. Promise is used to solve two problems:

★ Supports chain calls, which can solve the problem of callback regions
. Callback Hell: Nested calls of callback functions. The result of asynchronous execution of external callback functions is the condition for the execution of nested callbacks.
Callback Hell Disadvantages: It is not easy to read; it is not convenient for exception handling
. Specify a callback Functions are more flexible

6. Three disadvantages of Promise

1) Promise cannot be canceled, once it is created, it will be executed immediately, and it cannot be canceled halfway.
2) If the callback function is not set, the error thrown inside the Promise will not be reflected to the outside.
3) When it is in the pending (waiting) state, it cannot be obtained Know what stage you are in, whether it has just started or is about to be completed

7. Two characteristics of Promise

1) The state of the Promise object is not affected by the outside world.
2) Once the state of the Promise changes, it will not change again. This result can be obtained at any time, and the state cannot be reversed.

8. Promise asynchronous call instance

let p = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
    	resolve('OK');
    }, 1000);
});

p.then(value => {
    
    
    console.log(111);
    //有且只有一个方式(返回一个pending状态的Promise对象)
    return new Promise(() => {
    
    });
}).then(value => {
    
    
	console.log(222);
}).then(value => {
    
    
	console.log(333);
}).catch(reason => {
    
    
	console.warn(reason);
});

9. Promise, async, await execution sequence

async function async1(){
    
    
	console.log('async1 start')	//2  
    // 执行async2函数的 setTimeout
    await async2()
    setTimeout(function(){
    
    
        // 等上面执行完在执行
        console.log('setTimeout1')//8
	},0)
}		
async function async2(){
    
    
    setTimeout(function(){
    
    
    	console.log('setTimeout2')//7
    },0)
}
console.log('script start')//1    //执行同步代码
setTimeout(function(){
    
    
    // 最后执行setTimeout
    console.log('setTimeout3')//6
},0)
async1()  			//调用 
//执行先执行同步 输出2

// 调用
// 执行异步setTimeout
new Promise(function(r,j){
    
    
	console.log('Promise1')//3  //按照代码顺序
	r()
}).then(function(){
    
    
    // 等主线任务完成在执行
    console.log('Promise2')//5
})
console.log('script end')//4

10. Promise instance

console.log("start");

setTimeout(()=>{
    
    
	console.log("setTimeout");
},0);
    
new Promise((resolve,reject)=>{
    
    
	for(var i=0;i<5;i++){
    
    
    	console.log(i);
    }
    resolve() //修改promise状态为成功
}).then(()=>{
    
    
    console.log("promise回调函数");
})

console.log("end");
第一个宏任务队列
执行主线程上的代码
第二个宏任务
setTimeout
微任务队列
new Promise.then()
1、先执行主线程上的同步代码,输出start
2、遇到setTimeout将其加入到宏任务队列等待执行
3、遇到promise 立即执行,输出 01234
4、遇到promise的回调函数将其加入到微任务队列
5、执行主线程的同步代码,输出end
6、第一个宏任务队列执行完毕查看存在微任务队列,执行微任务队列中的任务,输出promise的回调函数
7、微任务执行完毕,执行下一个宏任务队列中的任务,输出setTimeout
输出:
start
0
1
2
3
4
end
promise回调函数
setTimeout

Supongo que te gusta

Origin blog.csdn.net/DZQ1223/article/details/131422587
Recomendado
Clasificación