Promise.then不执行

时间:2017-05-10 14:52:51

标签: javascript promise

仅在以下代码块中首先承诺'登录到控制台。这是为什么?我试图编写一个测试来弄清楚.tatch()在.catch()之后是如何执行的,但是除了第一个承诺之外什么也没有。怎么回事?

   function foo() {
      return new Promise((resolve, reject) => {
        return console.log('first promise')
      })
      .then(() => console.log('first then'))
      .catch(() => console.log('catch block'))
      .then(() => console.log('last block'))
      .then(() => resolve)
    }
    foo();

2 个答案:

答案 0 :(得分:5)

正如Yury所说,你不是在解决这个承诺,只是简单地返回一个日志。

https://jsfiddle.net/k7gL57t3/

 function foo() {
   var p1 = new Promise((resolve, reject) => {
     resolve("Test");
   })
   p1.then(() => console.log('first then'))
     .then(() => console.log('last block'))
     .then(() => resolve)
     .catch(() => console.log('catch block'));
 }
foo();

答案 1 :(得分:1)

我相信它是因为你的then链在Promise回调中没有关闭到resolve。试试这个:

function foo() {
    return Promise.resolve()
        .then(() => console.log('first then'))
        .catch(() => console.log('catch block'))
        .then(() => console.log('last block'));
}

或者如果你想使用Promise构造函数:

function foo() {
    return new Promise((resolve, reject) => {
        console.log('first promise');
        return resolve();
    })
        .then(() => console.log('first then'))
        .catch(() => console.log('catch block'))
        .then(() => console.log('last block'));
}