-1

So, I have this code base:

const axios = require('axios');

const req = axios.get('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQYnIfSxQXlLcfndCeenvH8kvgjKfaW51rQpTSR05fOYH6q8Rlt');


Promise.reject(req).then(null, () => {
    console.log('first error --- fired',);

    return new Error('Error')
});


// req is still fine here despite I have rejected it above 

req
    .then(() => {
        console.log('data --- okay');
    }).catch(() => {
    console.log('error ---  fired',);
})

Soo, after querying image I am rejecting req instance and expecting that req will be in rejected state, but instead it still in pending state and I can access it below my comment.

Why?

How may I reject it completely?

Thanks!

Nikita Shchypyplov
  • 1,090
  • 1
  • 9
  • 18

1 Answers1

5

Promise.reject returns a new promise and the parameter that you pass to reject is considered to be the reason why the new promise is rejected. It does not mark req as a rejected promise.

It looks like you're trying to use some sort of cancellation, which native promises don't support. You might look into the Bluebird promise library which does support cancellation, or as @DaveNewton suggests, leverage axios' own cancellation mechanism. You should also read Cancel a vanilla ECMAScript 6 Promise chain.

Here's a simple solution that could work in your scenario (mostly influenced by @MichaelYagudaev's answer on the linked question):

const cancellable = (other) => {
  let canceled = false;
  const ifCancelled = (res, rej) => val =>
    canceled ? rej(new Error('Canceled')) : res(val);
  const promise = new Promise((resolve, reject) => {
    other.then(ifCancelled(resolve, reject), ifCancelled(reject, reject));
  });
  promise.cancel = () => {
    canceled = true;
  };
  return promise;
};

const req = cancellable(fetch('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQYnIfSxQXlLcfndCeenvH8kvgjKfaW51rQpTSR05fOYH6q8Rlt'));

req.cancel();

req
  .then(() => {
    console.log('data --- okay');
  }).catch((err) => {
    console.log('error ---  fired', err.message);
  });
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331