Promise.then方法的执行顺序例题分析

1. 当Promise对象作为resolve的参数时

const p = Promise.resolve(); 
const p1 = Promise.resolve(p); //就是p
const p2 = new Promise(res => res(p)); //新建一个对象,对象状态依赖p
// res(p)可以看作 await p1; await resolve();
// 或者p.then(data => getData()).then(() => p2.resolve())

// 首先;p1 === p; p2!===p
// 那么,p1是一个fulfilled状态的对象;p2状态需要运行后求得
console.log(p === p1); // true
console.log(p === p2); // false

p1.then(() => {
    console.log('p1-1');
}).then(() => {
    console.log('p1-2');
}).then(() => {
    console.log('p1-3');
})
p2.then(() => { //p2.resolve之后才能调用回调函数
    console.log('p2-1');
}).then(() => {
    console.log('p2-2');
}).then(() => {
    console.log('p2-3');
})
p.then(() => {
    console.log('p-1');
}).then(() => {
    console.log('p-2');
}).then(() => {
    console.log('p-3');
})
//  运行结果
// getData()
p1-1
p-1
// resolve()
p1-2
p-2
p2-1
p1-3
p-3
p2-2
p2-3

2. 当Promise的resolve方法在另一个Promise对象的then方法中运行时,变异步;

let p3;
p1 = new Promise(resolve => {
    p3 = new Promise(res => res());
    p3.then(() => {
        console.log('p3')
        resolve(); // resolve()方法用在then方法中,变为异步执行
    })
})
p1.then(() => {
    console.log('p1-1');
}).then(() => {
    console.log('p1-2');
})
p3.then(() => {
    console.log('p3-1')
}).then(() => {
    console.log('p3-2')
})
// 运行结果如下:
p3
p3-1
p1-1
p3-2
p1-2

示例:

const p1 = Promise.resolve();
let p3;
const p2 = new Promise(function(resolve, reject){
    p3 = new Promise(res => res(p1));
    p3.then(() => {  //1 p3.then第一个
        console.log('p3')
        resolve('ok');
    })
});
p1.then(() => {
    console.log('p1-1')
}).then(() => {
    console.log('p1-2')
}).then(() => {
    console.log('p1-3')
})
p2.then(function(data) {
    console.log('p2-1')
}).then(function(data) {
    console.log('p2-2')
}).then(function(data) {
    console.log('p2-3')
})
// p3.then第二个,p3状态变化触发then方法时,同时触发,按照先后顺序执行
// 只要时p3.then(...)都同时触发
p3.then(function(data) { 
    console.log('p3-1')
}).then(function(data) {
    console.log('p3-2')
}).then(function(data) {
    console.log('p3-3')
})
// 运行结果
p1-1
p1-2
p3
p3-1
p1-3
p2-1
p3-2
p2-2
p3-3
p2-3

3. 当使用catch()方法捕获异常时

const p1 = Promise.resolve();
const p2 = Promise.reject(); //状态为rejected
p1.then(() => {
    console.log('p1-1')
}).then(() => {
    console.log('p1-2')
}).then(() => {
    console.log('p1-3')
})
p2.then(function(data) { //会立即触发,但是触发的是then中省略的第二个函数;
    console.log('p2-1')
}).then(function(data) {
    console.log('p2-2')
}).then(function(data) {
    console.log('p2-3')
}).catch(() => {
    console.log('catched')
})
//  运行结果如下:
p1-1
// 默认运行p2的第一个错误回调
p1-2
// 默认运行p2的第二个错误回调
p1-3
// 默认运行p2的第三个错误回调
catched

猜你喜欢

转载自www.cnblogs.com/lyraLee/p/11823354.html