gpt4 book ai didi

timeout - 提前捕获 Promise 的 TimeoutError

转载 作者:行者123 更新时间:2023-12-01 22:24:43 24 4
gpt4 key购买 nike

我有一个可以取消的 Bluebird promise 。当取消时,我必须做一些工作来巧妙地中止正在运行的任务。可以通过两种方式取消任务:通过 promise.cancel()promise.timeout(delay)

为了能够在取消或超时时巧妙地中止任务,我必须捕获 CancellationErrors 和 TimeoutErrors。捕获 CancellationError 是有效的,但由于某种原因我无法捕获 TimeoutError:

var Promise = require('bluebird');

function task() {
return new Promise(function (resolve, reject) {
// ... a long running task ...
})
.cancellable()
.catch(Promise.CancellationError, function(error) {
// ... must neatly abort the task ...
console.log('Task cancelled', error);
})
.catch(Promise.TimeoutError, function(error) {
// ... must neatly abort the task ...
console.log('Task timed out', error);
});
}

var promise = task();

//promise.cancel(); // this works fine, CancellationError is caught

promise.timeout(1000); // PROBLEM: this TimeoutError isn't caught!

如何在设置超时之前捕获超时错误?

最佳答案

当你取消一个 promise 时,只要发现 parent 仍然可以取消,取消就会首先冒泡到其 parent ,这与仅传播到 child 的正常拒绝有很大不同。

.timeout 做了一个简单的正常拒绝,它不做取消,所以这就是为什么不可能这样做。

您可以在延迟后取消:

var promise = task();
Promise.delay(1000).then(function() { promise.cancel(); });

或者在任务函数中设置超时:

var promise = task(1000);

function task(timeout) {
return new Promise(function (resolve, reject) {
// ... a long running task ...
})
.timeout(timeout)
.cancellable()
.catch(Promise.CancellationError, function(error) {
// ... must neatly abort the task ...
console.log('Task cancelled', error);
})
.catch(Promise.TimeoutError, function(error) {
// ... must neatly abort the task ...
console.log('Task timed out', error);
});
}
<小时/>

您还可以创建如下方法:

Promise.prototype.cancelAfter = function(ms) {
var self = this;
setTimeout(function() {
self.cancel();
}, ms);
return this;
};

然后

function task() {
return new Promise(function (resolve, reject) {
// ... a long running task ...
})
.cancellable()
.catch(Promise.CancellationError, function(error) {
// ... must neatly abort the task ...
console.log('Task cancelled', error);
})
}

var promise = task();

// Since it's a cancellation, it will propagate upwards so you can
// clean up in the task function
promise.cancelAfter(1000);

关于timeout - 提前捕获 Promise 的 TimeoutError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23538239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com