我最近一直在问自己如何使用 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 重现第一个用例吗?
烙印99
慕哥9229398
一只斗牛犬
随时随地看视频慕课网APP
相关分类