基本思路
- 使用
Promise
来封装每个异步任务,将其转化为可管理的状态。
- 利用
Promise.all
方法,该方法接受一个Promise
数组作为参数,当所有的Promise
都变为resolved
状态时,它返回的Promise
才会resolved
,并且会将所有Promise
的resolved
值组成一个数组返回;如果有任何一个Promise
变为rejected
状态,它返回的Promise
就会立即rejected
。
代码示例
function asyncTask(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(new Error('Request failed with status ' + xhr.status));
}
}
};
xhr.send();
});
}
const urls = ['https://example.com/api1', 'https://example.com/api2', 'https://example.com/api3'];
const tasks = urls.map(url => asyncTask(url));
Promise.all(tasks)
.then(responses => {
console.log(responses);
})
.catch(error => {
console.error('An error occurred:', error);
});