js 一个promise数组且该数组会随时添加新promise要怎么样一个一个同步执行?-灵析社区

庆广大

js 一个promise数组且该数组会随时添加新promise,要怎么样一个一个同步执行 有可能执行完一个promise过一会才会添加新的

阅读量:19

点赞量:0

问AI
原生不支持,自己控制 promise 就行了。 先写期待的用法: // 主进程 const myPromiseAll = new MyPromiseAll([...启动时的异步操作]); await myPromiseAll.promise; // 继续其它操作 // 事件函数 function onClick() { myPromiseAll.add(新异步操作); } 然后简单实现一下 "MyPromiseAll" 这个类: class myPromiseAll( promise; #tasks = 0; #count = 0; #resolve; #reject; constructor(tasks) { for (const task of tasks) { this.add(task); } this.promise = new Promise((resolve, reject) => { this.#resolve = resolve; this.#reject = reject; }); } add(task) { task.then(() => { this.#count++; if (this.#count >= this.#tasks) { this.#resolve(); } }).catch(err => { // this.#reject(); }); this.#tasks++; } } 没测,你自己根据需求改改吧。