如何给Promise添加进度通知的功能?
在 JavaScript 中,原生的 `Promise` 不支持进度通知功能,但我们可以通过自定义 Promise 或使用 `Progress` 事件来实现。以下是几种实现进度通知的方法。

### 方法 1: 自定义 Promise

我们可以创建一个自定义的 Promise 类,允许在执行过程中触发进度更新。

```javascript
class ProgressPromise {
constructor(executor) {
this.progress = 0; // 初始化进度
this.onProgressCallbacks = []; // 存储进度回调

this.promise = new Promise((resolve, reject) => {
executor(this.updateProgress.bind(this), resolve, reject);
});
}

// 更新进度并调用回调
updateProgress(progress) {
this.progress = progress;
this.onProgressCallbacks.forEach(callback => callback(progress));
}

// 添加进度回调
onProgress(callback) {
this.onProgressCallbacks.push(callback);
}
}

// 使用自定义 Promise
const myPromise = new ProgressPromise((updateProgress, resolve, reject) => {
let total = 100;

for (let i = 0; i <= total; i++) {
setTimeout(() => {
updateProgress(i); // 更新进度
if (i === total) resolve("完成");
}, i * 50); // 模拟异步操作
}
});

// 添加进度回调
myPromise.onProg
展开
评论