javascript - 异步/等待语法:有没有办法定义一个代码块在函数之后执行而不阻塞执行?
问题描述
我最近一直在问自己如何使用 async/await 语法重现 then/catch 的行为。
使用 then/catch,我可以定义一个回调,该回调仅在 Promise 解决时执行,然后像这样继续执行。
function test() {
getUsersFromDB().then(users => console.log(users));
console.log('The rest of the code here continues to execute');
[...]
// Promise resolves and logs the users value
}
对我来说,使用 async/await 你可以有两种可能的行为。
1.等待函数并阻塞其余的执行
async function test() {
const users = await getUsersFromDB();
// Code in here is not executed until promises returns
console.log(users);
}
2. 不要等待返回值,但不要期望你的承诺会在其余代码执行时实现
function test() {
const users = getUsersFromDB();
// May log undefined
console.log(users);
}
我可以使用 async/await 重现第一个用例吗?
解决方案
Usingthen
是最简单的解决方案,但您可以使用AIIFE:
function test() {
(async () => {
const users = await getUsersFromDB();
console.log(users);
})().catch(console.error);
console.log('The rest of the code here continues to execute');
[...]
// Promise resolves and logs the users value
}
替代方案只能是async do
表达式。
推荐阅读
- json - PowerShell 调用-WebRequest | API 调用
- r - 在 linux 环境中从命令行调用 RStudio 的命令是什么?
- java - 使用 Java 8 并行流以原子方式更新从 Map 检索的元素
- python - 将浮点值列表的小数精度格式化为以逗号作为小数分隔符的元组序列
- javascript - jQuery委派的.off()不起作用
- angular - Angular 5 的子路由无法正常工作
- unit-testing - 如何区分单元测试和集成测试?
- html - 怎么混与段落?
- php - angular http get 从 php 文件返回空的 json 数据
- exist-db - 存在-db如何访问pdf