帮我手写一个promise.all
时间: 2023-07-01 07:28:52 浏览: 38
好的,这里是一个简单的手写 Promise.all 的实现:
```javascript
function promiseAll(promises) {
return new Promise(function(resolve, reject) {
if (!Array.isArray(promises)) {
return reject(new TypeError('arguments must be an array'));
}
var resolvedCount = 0;
var promisesCount = promises.length;
var results = [];
promises.forEach(function(promise, index) {
Promise.resolve(promise).then(function(result) {
resolvedCount++;
results[index] = result;
if (resolvedCount === promisesCount) {
return resolve(results);
}
}).catch(function(error) {
return reject(error);
});
});
});
}
```
这个函数接收一个 Promise 数组,返回一个新的 Promise,当所有的 Promise 都完成时,返回一个结果数组,数组中的元素顺序与传入的 Promise 数组中的顺序一致。如果数组中的任意一个 Promise 被拒绝(rejected),则返回的 Promise 也会被拒绝,并且返回的错误是被拒绝的 Promise 的错误。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)