我使用以下类来路由我的所有API请求

class PromiseBroker {
    #promises = {};
    #overlayEle = document.getElementById('loading-overlay');
    constructor(){

    }
    get promises(){
        return this.#promises;
    }
    setPromise(key, value){
        this.promises[key] = value;
        this.#overlayEle.classList.remove('d-none');
        Promise.allSettled(Object.values(this.promises)).then(results => {
            this.#overlayEle.classList.add('d-none')
        });
    }
}

这个类的目的是在所有API请求完成后取消加载覆盖.我不知道会提前提出多少要求.我面临的问题是,随着promise 的增加,它将被过早地驳回.以下是我所指的:

  1. 添加了Promise A-添加了加载覆盖
  2. Promise A解决-取消加载覆盖
  3. 已添加Promise B-已添加加载覆盖
  4. 添加了Promise C
  5. Promise B解决-取消加载覆盖
  6. Promise C解决-这是我希望取消覆盖的时候

只有当所有promise (包括自allSettled呼叫以来增加的promise )都得到解决时,我才会放弃.我认为,问题在于,在等待和解promise 的同时,国家也在发生变化.我不知道是否有办法取消或改写allSettled,只使用最近的呼叫.

推荐答案

完全不要使用allSettled.只观察一次每个promise 的完成情况,并保留一组待定promise 的(关键):

const defaultUpdate = activeCount => {
    const overlay = document.getElementById('loading-overlay');.
    overlay.classList.toggle('d-none', activeCount == 0);
};

class PromiseBroker {
    #promises = {};
    #active = new Set();
    #update;
    constructor(update = defaultUpdate) {
         this.#update = update;
    }
    get promises(){
        return this.#promises;
    }
    get activeCount() {
       return this.#active.size;
    }
    setPromise(key, value) {
        this.promises[key] = value;
        this.#active.add(key);
        this.#update(this.activeCount);
        const done = () => {
            this.#active.delete(key);
            this.#update(this.activeCount);
        };
        Promise.resolve(value).then(done, done);
    }
}

Javascript相关问答推荐

如何在NightWatch.js测试中允许浏览器权限?

Plotly热图:在矩形上zoom 后将zoom 区域居中

react—router v6:路由没有路径

Angular material 拖放堆叠的牌副,悬停时自动展开&

将本机导航路由react 到导航栏中未列出的屏幕?

Websocket错误—有一个或多个保留位开启:reserved1 = 1,reserved2 = 0,reserved3 = 0

编剧如何获得一个div内的所有链接,然后判断每个链接是否都会得到200?

我创建了一个创建对象的函数,我希望从该函数创建的对象具有唯一的键.我怎么能做到这一点?

Angular 订阅部分相互依赖并返回数组多个异步Http调用

如何在Angular17 APP中全局设置AXIOS

WhatsApp Cloud API上载问题:由于MIME类型不正确而导致接收&Quot;INVALID_REQUEST";错误

每次重新呈现时调用useState initialValue函数

处理TypeScrip Vue组件未初始化的react 对象

用于测试其方法和构造函数的导出/导入类

在SuperBase JS客户端中寻址JSON数据

如何在Jest中模拟函数

无法使用Redux异步函数读取未定义的useEffect钩子的属性';map';

在每次重新加载页面时更改指针光标

在此div中添加一个类,并在一段时间后在Java脚本中将其删除

打字脚本中的函数包装键入