因此,我对异步JavaScript有点陌生,我无法弄清楚为什么.2之前要记录.2。
这里唯一的异步方法是 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()
。这种方法的一个优点是,它允许一次分派多个async
任务(即makePokemon
),而不是按顺序方式分派(如上述情况):
/* 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()
});
}
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句