promise·all
时间: 2023-10-28 21:01:21 浏览: 37
`Promise.all()` 是一个内置的 JavaScript 函数,它接受一个 Promise 数组作为参数,并返回一个新的 Promise 对象。这个新的 Promise 对象在数组中所有的 Promise 对象都成功 resolve 时才会 resolve,否则只要有一个 Promise 对象 reject,它就会 reject。
举个例子,假设我们有两个异步操作,分别是执行 HTTP 请求和读取本地文件,我们可以使用 `Promise.all()` 来同时等待这两个操作完成:
```javascript
const promise1 = fetch('https://example.com/data.json');
const promise2 = readFile('/path/to/file.txt');
Promise.all([promise1, promise2])
.then(([response, fileContent]) => {
console.log('Data from server:', response.json());
console.log('File content:', fileContent);
})
.catch(error => {
console.error('An error occurred:', error);
});
```
在上面的代码中,我们创建了两个 Promise 对象,一个是通过 `fetch()` 函数发送 HTTP 请求获取服务器数据的 Promise,另一个是通过 `readFile()` 函数读取本地文件的 Promise。然后我们把这两个 Promise 对象放在一个数组中,传给 `Promise.all()` 函数。`Promise.all()` 会等待这两个 Promise 对象都完成(即都 resolve 或都 reject)之后,返回一个新的 Promise 对象。在这个新的 Promise 对象 resolve 时,它会把每个原始 Promise 对象 resolve 的结果作为数组传递给 `.then()` 方法的回调函数,我们可以在回调函数中处理这些结果。如果其中任何一个原始 Promise 对象 reject,新的 Promise 对象就会 reject,我们可以在 `.catch()` 方法中捕获这个错误。