【发布时间】:2020-11-28 15:51:51
【问题描述】:
我是 javascript/typescript 的新手,我使用 typescript 编写二十一点应用程序,在一个玩家游戏中,我将机器人作为第二个玩家。 他的脚本是这样的:
const botTurn = (bot : Player) =>{
while(bot.Points < 21)
{
if(bot.Points < 18)
{
hitMe();
}
else
{
var random = Math.random();
if(random < 0.5)
{
hitMe();
}
else{
break;
}
}
}
stay();
}
hitMe 看起来像这样:
const hitMe = () =>
{
fetch('https://deckofcardsapi.com/api/deck/' + deckId + '/draw/?count=1')
.then(response => response.json())
.then(data => {
deckLenght = data.remaining;
for(let card of data.cards)
{
var newCard = getCardData(card);
players[currentPlayer].Hand.push(newCard);
renderCard(newCard, currentPlayer);
updatePoints();
updateDeckLenght();
check();
}
});
}
所以 botTurn 不会等待 hitMe 完成并且我的浏览器挂起 如何解决?
【问题讨论】:
-
你不能把异步函数写成同步的。考虑使用 async/await。
-
怎么做,就像我说的我是 ts 的新手?
标签: javascript typescript