Promise

389 阅读2分钟

日常 promise 虽然不复杂,但是面试的难免还是会有人给出一些刁钻的角度。还有就是对于错误的捕获处理,其实一直没有应用和理解。为了能全面的理解 promise,写了这篇文章。

实际上 mdn 中的这篇文章给出了很多例子,非常生动具体。Using_Promise 中说:

..., and catch(failureCallback) is short for then(null, failureCallback).

也就是说你可以把 catch 当成一个只有第二个参数的 then,这样一来的话,下面这段代码就能解释的通了。

new Promise((resolve, reject) => {
    console.log('Initial');

    resolve();
})
.then(() => {
    throw new Error('Something failed');

    console.log('Do this');
})
.catch(() => {
    console.error('Do that');
})
.then(() => {
    console.log('Do this, no matter what happened before');
});

Initial
Do that
Do this, no matter what happened before

下面这段代码也很有意思,可以虽然 p2 的第二个 then 比 p1 的第二个 then 注册的晚,但是实际上却是 p1 的第二个 then 先执行。可见 then 注册的早晚无关,只和 promise 的注册顺序有关。

setTimeout(() => console.log(0))

const p1 = new Promise((resolve) => {
  console.log(1)
  resolve(2)
  console.log(3)
}).then(o => console.log(o))

const p2 = new Promise(resolve => {
  console.log(4)
  resolve(5)
}).then(o => console.log(o))

p2.then(() => console.log(6))
p1.then(() => console.log(7))
const p1 = new Promise(resolve => {
  resolve(1);
}).then(data => console.log(data));

const p2 = new Promise(resolve => {
  resolve(2)
}).then(data => console.log(data));

p2.then(data => {
  console.log(3);
})
p2.then(data => {
  console.log(4);
})
p1.then(data => {
  console.log(5);
})

我感觉我还是没有完全理解 promise,比如下面两段代码的执行结果我就不是很理解。

// 代码一
const p1 = new Promise(resolve => {
  resolve(1);
}).then(data => console.log(data));

const p2 = new Promise(resolve => {
  resolve(2)
}).then(data => console.log(data));

p2.then(data => {
  console.log(3);
})
p2.then(data => {
  console.log(4);
})
p1.then(data => {
  console.log(5);
})
// 1 2 5 3 4
// 代码二
const p1 = new Promise(resolve => {
  resolve(1);
});

p1.then(data => console.log(data));

const p2 = new Promise(resolve => {
  resolve(2)
});

p2.then(data => console.log(data));

p2.then(data => {
  console.log(3);
})
p2.then(data => {
  console.log(4);
})
p1.then(data => {
  console.log(5);
})
// 1 2 3 4 5

promise 的问题就此中断一段时间,总的来说已经很清楚了,虽然有些变态的题目还是不一定能答得上来,但是对于 promise 的理解又进了一步。可以暂时终止了。

参考文章

  • juejin.cn/post/699796… ,这篇文章的内容可以说是非常好,从根本上解决了 promise 执行顺序的问题。如果这篇文章的内容能全部看懂的话,几乎就没有什么问题可以难得住你了。
  • juejin.cn/post/688312… ,这篇文章也不错