网络请求、定时器和文件读取不会立刻完成,需要通过 Promise 处理最终结果。
async function loadData(url) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5000);
try {
const response = await fetch(url, { signal: controller.signal });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} finally {
clearTimeout(timer);
}
}多个互不依赖的任务可以使用 Promise.all 并发执行。任何一个失败都会让 Promise.all 失败;如果需要保留所有结果,可以使用 Promise.allSettled。