簡體   English   中英

如何判斷頁面上是否有任何待處理(未完成)的 Promise

[英]How to tell if there are any pending (un-fulfilled) Promises on the page

我的頁面上有各種組件,它們執行各種 JavaScript 承諾。

在任何給定時間,我都想知道還有多少 Promise 未決(或者至少如果計數為 0 或 > 0)。

我已經看到Promise.all()被用作建議,但這些承諾並非全部同時觸發,因此不會通過一次調用Promise.all()

如果可能,我還想避免 jQuery 並探索任何原生 ES6 解決方案。

Chrome 現在有queryObjects(Promise) ,這有點尷尬 API 但似乎至少適用於您提出的字面問題:

> queryObjects(Promise)
undefined
Array(2)

Expand the array it logs to inspect the state of each promise, or right-click on it and select Store as global variable to be able to Promise.all() it.

我不知道 Firefox 有什么類似的東西。

要跟蹤一組特定的 Promise,您可以使用一個小助手,例如:

 const promiseTracker = () => ({
     count: 0,
     get isActive() { return this.count === 0; },
     track(p) {
        this.count += 1;
        p.then(() => this.count -= 1, () => this.count -= 1);
     }
 });

這可以用作:

 const networkCalls = promiseTracker();

 networkCalls.track(fetch(/*...*/));
 //...

 console.log(networkCalls.isActive); // ?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM