我想拒绝一个不是我做出的 promise 。也就是说,我读过的示例描述了类似的内容:
const sample = new Promise((resolve, reject) => {
setTimeout(() => {
reject('fail promise');
}, 1000);
});
1 秒后拒绝样本
。就我而言,我想要拒绝的 promise 是作为外部 api 调用而来的,那么我不能以这种方式拒绝。
我读过的另一种方法展示了如何将 Promise 与其他使用 setTimeout 来拒绝新 Promise 的 Promise 一起包装。像这样的事情:
const timeout = new Promise(function(resolve, reject) {
setTimeout(resolve, 1000, 'one');
});
const sample = new Promise(function(resolve, reject) {
setTimeout(resolve, 5000, 'two');
});
return Promise.race([sample, timeout]);
在返回另一个 promise 1 秒后强制“拒绝”sample
。这可以用来设置超时,但实际上它不会拒绝 sample
,只返回另一个 Promise,并且原始 Promise 继续运行,直到它拒绝或自行解决。
我找不到如何在没有库的情况下正确拒绝 promise
最佳答案
为什么你需要拒绝他们的 promise ?您关心的是为您的代码获得有用的结果,因此请编写能够获得该结果的代码。
将 API 调用包装在您自己的 Promise 中,对您的 Promise 进行超时拒绝,如果该 API 在超时之前产生结果,则传递 resolve
:
const attempt = new Promise( (resolve, reject) => {
// run the actual API _and_ your rejection timeout concurrently:
let rejected = false;
const id = setTimeout(() => {
rejected = true;
reject(new Error('timeout');
}), 1000);
actualApiCall(some, input, args, here)
.then(result => {
if (rejected) return; // <- if we rejected via timeout, we no longer care.
clearTimeout(id); // <- always remember to properly clean up
resolve(result);
})
.catch(e => {
if (rejected) return;
clearTimeout(id);
reject(e)
});
});
attempt
.then(result => doSomethingWith(result))
.catch(e => console.log('rejected:', e));
关于javascript - 拒绝 javascript Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59791934/