在 javascript 中查看所有未决的承诺 [英] View all pending promises in javascript
问题描述
在我的测试中,有时我会遇到超时,查看超时前挂起的承诺在哪里非常有用,这样我就知道哪些承诺最有可能处于始终挂起状态".
In my tests, sometimes I get timeouts, and it would be very useful to see what where the promises that were pending before the timeout, so that I know what promises have the most chances of being in an "always pending state".
有没有办法做到这一点?
Is there a way to do that ?
这是一个示例代码:
Promise.resolve().then(function firstFunction() {
console.log(1);
return 1;
}).then(function () {
return new Promise(function secondFunction(resolve, reject) {
// NEVER RESOLVING PROMISE
console.log(2);
});
}).then(function thirdFunction() {
// function that will never be called
console.log(3);
})
setTimeout(function timeoutTest() {
const pendingPromises = [];// ??????????? how do I get the pendingPromises
console.log(pendingPromises);
process.exit();
}, 5000);
如果可能的话,我想在 pendingPromises
中获取函数的名称和承诺 secondFunction
的堆栈跟踪,因为它永远不会解析.
I would like, if possible, to get in pendingPromises
the name of the function and stacktrace of the promise secondFunction
, since it is the one that will never resolve.
推荐答案
promise 链被设计成循序渐进地沿着成功路径传递价值或沿着错误路径传递原因".它不是为了在某个任意时间点查询被它吸收的个人承诺状态的快照".
A promise chain is designed progressively to deliver values down its success path or a "reason" down its error path. It is not designed to be enquired at some arbitrary point in time for a "snapshot" the state of individual promises that are assimilated by it.
因此,承诺链没有提供自然"的方式来完成您的要求.
Therefore, a promise chain offers no "natural" way to do what you ask.
你需要设计一个机制:
- 注册感兴趣的承诺.
- 跟踪每个已注册承诺的状态(如果承诺实现尚未提供).
- 按需检索已注册的 promise,按状态过滤.
沿着这些路线的构造函数将完成这项工作:
A constructor along these lines will do the job :
function Inspector() {
var arr = [];
this.add = function(p, label) {
p.label = label || '';
if(!p.state) {
p.state = 'pending';
p.then(
function(val) { p.state = 'resolved'; },
function(e) { p.state = 'rejected'; }
);
}
arr.push(p);
return p;
};
this.getPending = function() {
return arr.filter(function(p) { return p.state === 'pending'; });
};
this.getSettled = function() {
return arr.filter(function(p) { return p.state !== 'pending'; });
};
this.getResolved = function() {
return arr.filter(function(p) { return p.state === 'resolved'; });
};
this.getRejected = function() {
return arr.filter(function(p) { return p.state === 'rejected'; });
};
this.getAll = function() {
return arr.slice(0); // return a copy of arr, not arr itself.
};
};
问题所需的唯一方法是 .add()
和 .getPending()
.提供其他内容是为了完整性.
The only methods required by the question are .add()
and .getPending()
. The others are provided for completeness.
你现在可以写:
var inspector = new Inspector();
Promise.resolve().then(function() {
console.log(1);
}).then(function() {
var p = new Promise(function(resolve, reject) {
// NEVER RESOLVING PROMISE
console.log(2);
});
return inspector.add(p, '2');
}).then(function() {
// function that will never be called
console.log(3);
});
setTimeout(function() {
const pendingPromises = inspector.getPending();
console.log(pendingPromises);
process.exit();
}, 5000);
Inspector
的使用不仅限于承诺链所吸收的承诺.它可以用于任意一组承诺,例如一组与 Promise.all()
聚合的:
The use of Inspector
isn't confined to promises assimilated by promise chains. It could be used for any arbitrary set of promises, for example a set to be aggregated with Promise.all()
:
promise_1 = ...;
promise_2 = ...;
promise_3 = ...;
var inspector = new Inspector();
inspector.add(promise_1, 'promise 1');
inspector.add(promise_2, 'promise 2');
inspector.add(promise_3, 'promise 3');
var start = Date.now();
var intervalRef = setInterval(function() {
console.log(Date.now() - start + ': ' + inspector.getSettled().length + ' of ' + inspector.getAll().length + ' promises have settled');
}, 50);
Promise.all(inspector.getAll()).then(successHandler).catch(errorHandler).finally(function() {
clearInterval(intervalRef);
});
这篇关于在 javascript 中查看所有未决的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!