本文阅读时间大概 2 分钟javascript
await
、return
和 return await
有不少容易被忽视的不一样之处。java
首先定义一个异步函数:git
async function waitAndMaybeReject() {
// 等待1秒
await new Promise(r => setTimeout(r, 1000));
const isHeads = Boolean(Math.round(Math.random()));
if (isHeads) {
return 'yay';
} else {
throw Error('Boo!');
}
}
复制代码
函数等待 1 秒钟,而后有一半的几率返回 "yay"
,一半的几率抛出异常。github
async function foo() {
try {
waitAndMaybeReject();
}
catch (e) {
return 'caught';
}
}
复制代码
直接调用 foo
,函数老是返回 Promise fulfill with undefined, without waiting。dom
永远不会返回 "yay"
。异步
async function foo() {
try {
await waitAndMaybeReject();
}
catch (e) {
return 'caught';
}
}
复制代码
调用 foo
,函数返回的 Promise 等待 1 秒,而后 fulfill with undefined
, or fulfill with "caught"
。async
由于咱们 await waitAndMaybeReject()
的结果,若是 rejected,咱们的 catch 块捕获了异常,而后 "caught"
,若是 fulfilled,咱们的函数并无返回 Promise 的值。函数
async function foo() {
try {
return waitAndMaybeReject();
}
catch (e) {
return 'caught';
}
}
复制代码
调用 foo
,函数返回的 Promise 等待 1 秒,而后 fulfill with "yay"
, or reject with Error('Boo!')
。工具
async function foo() {
try {
return await waitAndMaybeReject();
}
catch (e) {
return 'caught';
}
}
复制代码
调用 foo
,函数返回的 Promise 等待 1 秒,而后 fulfill with "yay"
, or fulfill with "caught"
。学习
这个是最符合咱们预期的写法。
咱们能够把它拆分一下:
async function foo() {
try {
// 等待 waitAndMaybeReject() 函数的结果
// 把 fulfilled value 赋值给 fulfilledValue:
const fulfilledValue = await waitAndMaybeReject();
// 若是 waitAndMaybeReject() 失败,抛出异常:
return fulfilledValue;
}
catch (e) {
return 'caught';
}
}
复制代码
dev-reading/fe 是一个阅读、导读、速读的 repo,不要依赖于 dev-reading/fe 学习知识。本 repo 只是一个快速了解文章内容的工具,并不提供全文解读和翻译。你能够经过本平台快速了解文章里面的内容,找到感兴趣的文章,而后去阅读全文。
阅读原文:await vs return vs return await
讨论地址:await、return 和 return await 的陷阱 #12
若是你想参与讨论,请点击这里