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

我最近一直在问自己如何使用 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
浏览 143回答 2
2回答

慕哥9229398

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表达式。

一只斗牛犬

所以你需要的基本上是拆分代码。一件应该以 async/await 语法执行,另一件应该照常执行。首先我想说的话,如果你这样做如下async function test() {   console.log('The rest of the code here continues to execute');      const users = await getUsersFromDB();   // Code in here is not executed until promises returns   console.log(users);}这样就可以了。这可能看起来有点奇怪,因为我们只是将线路向上移动了一点,这不是我们想要做的,但是......await关键字停止函数的执行async,但是我们有一些代码在冻结函数时应该继续工作await,这意味着我们不能将代码放在 之后await,只能放在之前。据我了解,表示为“这里的其余代码继续执行”的代码也可以是异步的,因此生成的示例如下:async function test() {   console.log('Some synchronous code');      setImmediate(() => {        console.log('Some asynchronous code');    });   const users = await getUsersFromDB();   // Code in here is not executed until promises returns   console.log(users);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript