async/await 是 JavaScript 处理异步的语法糖,async 函数自动返回 Promise,await 暂停函数执行等待 Promise 完成且不阻塞主线程,需在 async 函数内使用并配合 try/catch 错误处理,并发请求应优先用 Promise.all。

async/await 是 JavaScript 中处理异步操作的语法糖,它让异步代码看起来像同步代码,更易读、易维护。核心在于:用 async 声明函数,用 await 暂停执行、等待 Promise 完成,期间不阻塞主线程。
在函数声明前加 async,该函数就变成异步函数,无论内部是否含 await,它都会自动包装返回值为 Promise:
return 42)→ 等价于 Promise.resolve(42)
throw new Error())→ 等价于 Promise.reject(...)
Promise.resolve(undefined)
await 后面必须跟一个 Promise(或任何值,会被自动转为 resolved Promise),它会“暂停”当前 async 函数的执行,等 Promise settle(fulfilled 或 rejected)后再继续。注意:await 不阻塞整个线程,只是暂停当前函数逻辑,其他任务仍可运行。
const data = await fetch('/api/user').then(r => r.json())
await doSomething()(会报 SyntaxError)相比链式调用中的 .catch(),await 更自然地配合 try/catch 使用:
立即学习“Java免费学习笔记(深入)”;
async function getUser() {
try {
const res = await fetch('/api/user');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const user = await res.json();
return user;
} catch (err) {
console.error('获取用户失败:', err.message);
throw err; // 可选择重新抛出供上层处理
}
}如果多个异步操作彼此独立,不要连续 await,否则变成串行(耗时相加)。应先发起所有 Promise,再 await 它们:
const a = await api1(); const b = await api2();
const [a, b] = await Promise.all([api1(), api2()]);
Promise.allSettled(),它不会因某个失败而中断以上就是javascript async/await怎么用_如何用同步的方式写异步代码的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号