如何防止Promise进一步执行?

时间:2019-05-23 19:02:11

标签: javascript es6-promise

因此,我有以下代码库:

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,查询完图像后,我拒绝了req实例,并期望req处于拒绝状态,但是它仍然处于pending状态,我可以在评论下方访问它。

为什么?

我怎么能完全拒绝呢?

谢谢!

1 个答案:

答案 0 :(得分:5)

Promise.reject返回一个新承诺,并且您传递给reject的参数被视为原因,为什么新的承诺被拒绝。它没有将req标记为被拒绝的承诺。

您似乎正在尝试使用某种形式的取消,这是本机诺言不支持的。您可能会研究支持取消的Bluebird Promise库,或者如@DaveNewton建议的那样,利用axios自己的cancellation机制。您还应该阅读Cancel a vanilla ECMAScript 6 Promise chain

这是一个适用于您的情况的简单解决方案(主要受链接问题上的@MichaelYagudaev's answer的影响):

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