首页 > 解决方案 > 异步/等待语法:有没有办法定义一个代码块在函数之后执行而不阻塞执行?

问题描述

我最近一直在问自己如何使用 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 重现第一个用例吗?

标签: javascriptasync-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表达式


推荐阅读