Tracking/Logging 承诺

Tracking/Logging Promises

我正在尝试寻找跟踪 Promises 的解决方案。

我正在处理的项目有一些悬而未决的异步任务,这些任务不是 awaited/yielded。我正试图找到这样的案例,因为这些悬而未决的调用正在干扰测试套件。

我的一个方法是用 SinonJS 间谍监视全局 Promise 构造函数。但是在包装构造函数时,Promise 对象的属性会被间谍获取 hidden/overwritten,从而导致 Promises 无法使用。

const spier = sinon.spy(global, 'Promise')

也许我可以利用一些全局跟踪(例如事件循环或实时 Promises 的通用数组)。

或者也许有人对 Promise 有更多的了解,可以推荐可访问的内部 Promise 函数的替代监视点。

想听听您是否有任何类似的需求和您的方法。

您可以像这样猴子修补 promise 构造函数:

const global = window; // (in browser...)
const OldPromise = global.Promise; 
global.Promise = class Promise extends OldPromise {
    constructor(executor) {
    // do whatever you want here, but must call super()
    console.log('hello, promise');

    super(executor); // call native Promise constructor
  }
};

Promise.resolve();

来源: