查看javascript中所有挂起的承诺

View all pending promises in javascript

本文关键字:挂起 承诺 javascript 查看      更新时间:2023-09-26

在我的测试中,有时会出现超时,查看在超时之前挂起的承诺在哪里是非常有用的,这样我就知道哪些承诺最有可能处于"始终挂起状态"

有办法吗?

下面是一个示例代码:

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的函数名称和堆栈跟踪,因为它是永远不会解析的。

承诺链是逐步设计的,以便在其成功路径上传递值,或者在其错误路径上传递"原因"。它的设计目的不是为了在任意时间点查询被它吸收的单个承诺的"快照"状态。

因此,承诺链不提供"自然"的方式来完成你的请求。

你需要设计一个机制:

  • 登记利益承诺
  • 跟踪每个注册承诺的状态(如果承诺实现没有提供)。
  • 根据需要检索已注册的承诺,并按状态进行过滤。

这样的构造函数可以完成工作:

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()方法。为完整起见,提供了其他选项。

你现在可以写:

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()聚合的一组承诺:

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

我建议使用Bluebird这样的库,它比本机承诺快6倍,提供有用的警告和额外有用的方法,如- timeout,这可能会帮助你解决这个问题。