promise遇到的问题

472 阅读1分钟

promise的疑惑

为什么promise resolve了一个value, 最后输出的value值确是undefined

const test = new MPromise((resolve, reject) => {
    setTimeout(() => {
        resolve(111);
    }, 1000);
}).then((value) => {
    console.log('then');
});

setTimeout(() => {
    console.log(test);
}, 3000)

打印结果:

image.png 答案:因为现在这种写法, 相当于在.then里return undefined, 所以最后的value是undefined. 如果显式return一个值, 就不是undefined了;比如return value.

.then返回的是一个新Promise, 那么原来promise实现的时候, 用数组来存回调函数有什么意义?

这个问题提出的时候, 应该是有一个假定条件, 就是链式调用的时候.

这个时候, 每一个.then返回的都是一个新promise, 所以每次回调数组FULFILLED_CALLBACK_LIST都是空数组.

针对这种情况, 确实用数组来存储回调没意义, 完全可以就用一个变量来存储。

const test = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(111);
    }, 1000);
}).then((value) => {
    
}).then(() => {

})

答案:但是还有一种promise使用的方式, 这种情况下, promise实例是同一个, 数组的存在就有了意义

const test = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(111);
    }, 1000);
})
test.then(() => {});
test.then(() => {});
test.then(() => {});
test.then(() => {});

为什么我在catch的回调里, 打印promise, 显示状态是pending

const test = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject(111);
    }, 1000);
}).catch((reason) => {
    console.log('报错' + reason);
    console.log(test)
});

setTimeout(() => {
    console.log(test);
}, 3000)

打印:

image.png 答案:

  1. catch 函数会返回一个新的promise, 而test就是这个新promise
  2. catch 的回调里, 打印promise的时候, 整个回调还并没有执行完成(所以此时的状态是pending), 只有当整个回调完成了, 才会更改状态
  3. catch 的回调函数, 如果成功执行完成了, 会改变这个新Promise的状态为fulfilled