0

how to reject wrapper promise from inside one or? in other words, how to make number '3' never printed? Current output:

1
2
3

Expected output:

1
2
new Promise(function(resolve, reject) {
  console.log(1)
  resolve()
})
.then(() => console.log(2))
.then(() => { // how to reject this one if internal fails?
  new Promise(function(resolve, reject) {
    reject(new Error('Polling failure'));
  })
  .then(() => console.log(21))
})
.then(() => console.log(3))
sig
  • 267
  • 1
  • 10

2 Answers2

2

It looks like you're just missing a return

new Promise(function(resolve, reject) {
    console.log(1)
    resolve()
  })
  .then(() => console.log(2))
  .then(() => { // how to reject this one if internal fails?
    return new Promise(function(resolve, reject) {
        reject(new Error('Polling failure'));
      })
      .then(() => console.log(21))
  })
  .then(() => console.log(3))
Jude Fernandes
  • 7,437
  • 11
  • 53
  • 90
1

In order to reject a promise chain from a .then() handler, you need to either:

Use throw

Throwing any value will mark the promise as unsuccessful:

const p = new Promise(function(resolve, reject) {
  console.log(1)
  resolve()
})
.then(() => console.log(2))
.then(() => { throw new Error(); })
.then(() => console.log(3));


p
  .then(() => console.log("sucessful finish"))
  .catch(() => console.log("error finish"));

Return a rejected promise

The easiest way is with Promise.reject:

const p = new Promise(function(resolve, reject) {
  console.log(1)
  resolve()
})
.then(() => console.log(2))
.then(() => Promise.reject("problem"))
.then(() => console.log(3));


p
  .then(() => console.log("sucessful finish"))
  .catch(() => console.log("error finish"));
VLAZ
  • 26,331
  • 9
  • 49
  • 67