简体   繁体   English

异步/等待语法:有没有办法在 function 之后定义要执行的代码块而不阻塞执行?

[英]Async/await syntax: Is there a way to define a block of code to execute after a function without blocking the execution?

I've been questionning myself recently on how to reproduce a behaviour of then/catch with an async/await syntax.我最近一直在问自己如何使用 async/await 语法重现 then/catch 的行为。

With then/catch, I can define a callback which is only executed when the Promise resolves and then continue the execution like so.使用 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
}

For me, with async/await you can have 2 possible behaviours.对我来说,使用 async/await 你可以有两种可能的行为。

1. Wait for the function and block the rest of the execution 1. 等待 function 并阻塞 rest 的执行

async function test() {
   const users = await getUsersFromDB();
    // Code in here is not executed until promises returns
    console.log(users);
}

2. Don't wait for the return value but don't expect you promise to be fulfilled when the rest of the code executes 2.不要等待返回值,但不要指望你的promise在代码的rest执行时完成

function test() {
    const users = getUsersFromDB();
    // May log undefined
    console.log(users);
}

Can I reproduce the first use case using async/await?我可以使用 async/await 重现第一个用例吗?

Using then is the simplest solution, but you can use an AIIFE :使用then是最简单的解决方案,但您可以使用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
}

An alternative could only be async do expressions .另一种选择只能是async do表达式

So what you need is basically split the code.所以你需要的基本上是拆分代码。 One piece should be executed in async/await syntax, and another one should be as usual.一件应该以 async/await 语法执行,另一件应该照常执行。

First what I want to say, if you do as follows首先我想说的话,如果你这样做如下

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);
}

that will do the trick.这样就可以了。 This may appear a little strange because we just moved the line a bit up, this is not what we wanted to do, but...这可能看起来有点奇怪,因为我们只是将线路向上移动了一点,这不是我们想要做的,但是......

The await keyword stops execution of an async function, but we have some code that should continue working at the time when await freezes the function, that means we can't place the code after await , only before. await关键字停止执行async function,但是我们有一些代码应该在await冻结 function 时继续工作,这意味着我们不能将代码放在await之后,只能放在之前。

As far as I understand, the code tahat is indicated as "The rest of the code here continues to execute" can be asynchronous too, so the resulting example will be as follows:据我了解,代码tahat表示为“此处代码的rest继续执行”也可以是异步的,因此生成的示例如下:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在异步等待函数中引发错误后停止执行代码 - Stop Execution of Code After Error thrown in Async Await function 即使使用等待/异步,执行顺序也不正确。 内部代码完成后可以执行外部代码吗? - Even with await/async, execution order is not right. Can I do to execute the outer code after inner code finished? Async function await 后不触发代码 - Async function does not trigger the code after await Promises - 如何在没有 async / await 的情况下使异步代码同步执行? - Promises - How to make asynchronous code execute synchronous without async / await? 有没有办法将等待/异步 try/catch 块包装到每个函数? - Is there a way to wrap an await/async try/catch block to every function? 定义了“异步”功能而没有相应的“等待”语法的示例 - Example of an 'Async' Function Being Defined Without Corresponding 'Await' Syntax 使用async / await在fs.writeFile之后执行代码 - Execute code after fs.writeFile using async/await 从 async/await 块中提取部分代码到一个单独的函数中 - Extract part of code from an async/await block into a separate function 使用 async 一个接一个地执行一个 function 并等待反应 - Execute one function after another using async and await in react 异步等待正在阻止其他 function 运行 - Async await is blocking other function from running
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM