JavaScript:简单的异步问题

标签 javascript asynchronous

所以我对异步 JavaScript 有点陌生,我不明白为什么 '.2' 在 '.1' 之前记录日志。

这里唯一的异步方法是makePokemon()

我的目标是所有 '.1' 的日志都在 '.2' 之前。谢谢

                sender.room().forEach(async (client) => {
                    const pokemon = await makePokemon(client.getPokemon());
                    client.setPokemon(pokemon);
                    console.log('.1');
                });
                sender.room().forEach(client => {
                    console.log('.2');
                    client.emit('redirect', {
                        yourPokemon: client.getPokemon(),
                        theirPokemon: client.getOpponent().getPokemon()
                    });
                });

最佳答案

我的理解是,当在浏览器中使用 forEach() 时,期望回调将同步执行。

但是您可以按如下方式修改您的代码(前提是父函数声明为 async):

/* 
The following changes require the calling function to be async

async function foo() { */

/* Express iteration with for..of to achieve desired behavior */
for(const client of sender.room()) {
  
  const pokemon = await makePokemon(client.getPokemon());
  client.setPokemon(pokemon);
  console.log('.1');

}

for(const client of sender.room()) {
  console.log('.2');
  client.emit('redirect', {
    yourPokemon: client.getPokemon(),
    theirPokemon: client.getOpponent().getPokemon()
  });
}

/* } */

或者,正如 Patrick Roberts 指出的那样,您可以使用 Promise.all() 部分表达此逻辑。这种方法的一个优点是它允许一次分派(dispatch)多个异步任务(即makePokemon),而不是按顺序分派(dispatch)(如上例):

/* Map each client to a promise and execute all with Promise.all() */
Promise.all(sender.room().map(async(client) => {
  const pokemon = await makePokemon(client.getPokemon());
  client.setPokemon(pokemon);
  console.log('.1');
}))
/* If all prior promises are resolved, continue with next iteration */
.then(() => {

    for (const client of sender.room()) {
      console.log('.2');
      client.emit('redirect', {
        yourPokemon: client.getPokemon(),
        theirPokemon: client.getOpponent().getPokemon()
      });
    }
})

关于JavaScript:简单的异步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61436985/

相关文章:

javascript - react 错误 : "could not find the ' store' in the context of . ..”

javascript - 使用 jQuery 分配 CSS 变量

javascript - Node、MongoDB 和 Promise 的问题

javascript - 使用 jQuery 获取 url 并提取 url 段

javascript - 重定向并获取 "Leaving this page"警报框

c# - 当我的任务从自定义 TaskScheduler 启动时,'await' 不返回

hadoop - 绕过hadoop中Mapreduce作业的洗牌阶段?

firebase - 如何在循环中使用Future/Async函数? ( Dart/flutter )

ajax - 如何在不使用 'async: false' 和回调的情况下等待 ajax 调用完成?

sql - 多次请求后 NodeJS 无限期挂起