原生不支持,自己控制 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++;
}
}
没测,你自己根据需求改改吧。