(Javascript)为什么捕获不捕获拒绝?

时间:2018-12-07 07:12:20

标签: javascript ecmascript-6 es6-promise

下面是promise链接代码:

new Promise(function(resolve, reject) {
  console.log('first');
  resolve('yes');
}).then(
  new Promise(function(resolve, reject) {
    console.log('second');
    reject('no');
  })
).catch(rej => console.log(rej));

输出为:

“第一”

“第二”

我希望得到一个'no'输出,但是没有。 我不知道为什么抓住没有抓住第二个.then()的拒绝?

1 个答案:

答案 0 :(得分:4)

.then仅接受功能作为参数-您的

then(new Promise

正在将第二个.then传递给 Promise (在创建Promise链时,而不是在先前的Promise解析时,它会初始化*)。但是.then不知道在传递Promise时该怎么做,它只处理 function 参数。

相反,传递.then一个函数,并让该函数创建要返回的Promise,它将被正确捕获:

new Promise(function(resolve, reject) {
  console.log('first');
  resolve('yes');
}).then(
  () => new Promise(function(resolve, reject) {
//^^^^^^
    console.log('second');
    reject('no');
  })
).catch(rej => console.log('catch: ' + rej));

相关问题