繁体   English   中英

Promise.then不执行

[英]Promise.then not executing

在以下代码块中,仅将“第一个承诺”记录到控制台。 这是为什么? 我试图编写一个测试来弄清楚.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();

正如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();

我相信这是因为你的then链没有封闭来resolve Promise回调内部。 尝试这个:

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'));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM