如何阻止 Promise 进一步执行?
How may I prevent Promise from further execution?
所以,我有这个代码库:
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
将处于拒绝状态,但它仍处于 pending
状态,我可以在评论下方访问它。
为什么?
怎样才能完全拒绝?
谢谢!
Promise.reject
returns 一个 new promise 并且你传递给 reject
的参数被认为是 reason 拒绝新承诺的原因。它 不会 将 req
标记为已拒绝的承诺。
您似乎在尝试使用某种取消,本机承诺不支持。您可能会查看 Bluebird promise library which does support cancellation, or as @DaveNewton suggests, leverage axios' own mechanism. You should also read .
这是一个可以在您的场景中使用的简单解决方案(主要受 链接问题的影响):
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);
});
所以,我有这个代码库:
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
将处于拒绝状态,但它仍处于 pending
状态,我可以在评论下方访问它。
为什么?
怎样才能完全拒绝?
谢谢!
Promise.reject
returns 一个 new promise 并且你传递给 reject
的参数被认为是 reason 拒绝新承诺的原因。它 不会 将 req
标记为已拒绝的承诺。
您似乎在尝试使用某种取消,本机承诺不支持。您可能会查看 Bluebird promise library which does support cancellation, or as @DaveNewton suggests, leverage axios' own
这是一个可以在您的场景中使用的简单解决方案(主要受
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);
});