所以我对异步 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/