admin管理员组

文章数量:1278852

In the following code block only 'first promise' is logged to console. Why is that? I was trying to write a test to figure out how .then()'s execute after .catch() but was surprised when nothing besides the first promise ran. Whats going on here?

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

In the following code block only 'first promise' is logged to console. Why is that? I was trying to write a test to figure out how .then()'s execute after .catch() but was surprised when nothing besides the first promise ran. Whats going on here?

   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();
Share Improve this question asked May 10, 2017 at 14:52 sunnyharrissunnyharris 1151 gold badge1 silver badge6 bronze badges 1
  • 5 You never resolve nor reject initial promise. – Yury Tarabanko Commented May 10, 2017 at 14:55
Add a ment  | 

2 Answers 2

Reset to default 6

As Yury said, you're not resolving the promise, simply returning a log.

https://jsfiddle/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();

I believe it's because your then chain does not have closure to resolve inside of the Promise callback. Try this:

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

or this if you want to use the Promise constructor:

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

本文标签: javascriptPromisethen not executingStack Overflow