正在加载...

async 与 await

async 函数让异步步骤可以按顺序阅读。await 只在当前函数中等待 Promise,不会冻结页面,也不会停止其他 JavaScript。

await 暂停什么

执行到 await 时,函数暂时把控制权交还浏览器,其他事件仍可运行。Promise 完成后,函数从原位置继续。

async 调用始终返回 Promise

即使函数返回字符串,调用结果仍是以该字符串兑现的 Promise。函数抛出错误时,Promise 会被拒绝。

在 await 后读取结果

pour 返回 Promise。serve 先写入 waiting,等待完成后再取得 lida tea。

serve 中的 await

javascript
function pour(order) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
if (order === "") reject("no leaves");
else resolve(order + " tea");
}, 100);
});
}
async function serve() {
console.log("waiting");
let drink = await pour("lida");
console.log(drink);
}
serve();

输出依次是 waiting 和 lida tea。两行都在 serve 中,但第二行要等 Promise 完成。

调用者拿到 Promise

不使用 await 调用 serve(),不会直接得到饮料。

async 调用返回 Promise

javascript
async function serve() {
return "lida tea";
}
let ticket = serve();
console.log(ticket instanceof Promise);

输出为 true,说明 ticket 是 Promise。可在另一个 async 函数中 await,也可使用 then 读取值。

用 try 和 catch 处理拒绝

被等待的 Promise 一旦拒绝,就像在 await 位置抛出错误。请把操作放进 try。

捕获等待中的拒绝

javascript
function pour(order) {
return order === ""
? Promise.reject("no leaves")
: Promise.resolve(order + " tea");
}
async function serveEmpty() {
try {
await pour("");
} catch (reason) {
console.log(reason);
}
}
serveEmpty();

输出为 no leaves。同一 try 块中后续抛出的错误也会进入这个 catch。

页面其余部分继续运行

只有当前 async 函数会等待。调用会立刻返回 Promise,因此后面的同步代码仍可继续。

完整浏览器示例

示例在一个 async 函数中记录各阶段,并用短计时器兑现 Promise,无需服务器。

完整 async 页面

html
<!DOCTYPE html>
<html>
<body>
<p id="cup">blank</p>
<p id="line">…</p>
<script>
function pour(order) {
return new Promise(resolve => setTimeout(() => resolve(order + " tea"), 100));
}
async function serve() {
const cup = document.getElementById("cup");
const seen = ["waiting"];
cup.textContent = "waiting";
const drink = await pour("lida");
cup.textContent = drink;
seen.push(drink, "done");
document.getElementById("line").textContent = seen.join(" / ");
}
serve();
</script>
</body>
</html>

最终一行是 waiting / lida tea / done。写入等待结果后才会加入 done。

动手试试

修改 lida 并等待结果;再传入空字符串,确认 catch 得到 no leaves。

常见错误

不要期待 async 调用立刻返回字符串,不要在普通函数中使用 await,也不要误以为它会停止整个页面。

小结

async 始终返回 Promise。await 只暂停当前函数,直到 Promise 确定结果。可能被拒绝的操作应配合 try/catch。

🧠 测试您的知识

准备开始

测试您的知识

通过这个互动测验挑战自己,看看你对这个主题的理解程度如何

❓
6
问题
🎯
70%
及格要求
♾️
∞
时间
🔄
∞
尝试次数

📝 说明

  • 仔细阅读每个问题
  • 为每个问题选择最佳答案
  • 您可以随时重新参加测验
  • 您的进度将显示在顶部