异步函数不会在 while 循环中运行,直到循环中断

时间:2021-04-10 20:07:47

标签: javascript node.js api asynchronous async-await

我正在为 node.js 中的纸牌游戏编写一个简单的程序。目前,我只是在测试它,所以我使用 CLI 来获取用户输入(使用 prompt-sync 库)。当我询问用户是否想要另一张卡片时,有一个小问题,因为我们不知道用户想要一张卡片多少次,我将要求用户输入的函数包装在一个 while 循环中。循环如下...

            let player_score = getValues(deck_information.players_cards);
            let dealer_score = getValues(deck_information.dealers_card);
            let continue_asking = true;

            while (getInput(`You currently have ${player_score} and the dealer has ${dealer_score}. Would you like to hit?`)) {
                console.log(player_score);
                console.log(dealer_score);
                dealCards(deck_information.deck_id)
                    .then(addedValue => {
                        console.log("executes")
                        player_score += addedValue;
                        console.log(player_score);
                    })
                    .catch(err => {
                        console.log(err.message);
                    })
            }

“getInput”和“dealCards”方法主体区域如下...

const getInput = (text) => {
    let guess = prompt(text);

    if (guess === 'y' || guess === 'Y') {

        return true;
    }
    return false;

}
const dealCards = async (deck_identifier) => {
    const dealtCardsResp = await axios.get(`https://deckofcardsapi.com/api/deck/${deck_identifier}/draw/?count=1`);
    return getValues(dealtCardsResp.data.cards);
}

'getValues' 只是一个函数,用于检查给定卡片的面额并将其作为数字返回。

问题陈述 当我运行这个程序时,它会发出前两张牌,并在提示用户以下消息时

You currently have ${player_score} and the dealer has ${dealer_score}. Would you like to hit?

player_score 是玩家的分数,dealer_score 是庄家的分数。

这在意料之中,但是,当我输入“y”来处理下一张牌时,它只是一次又一次地提示用户问题(每次输入“y”时)

当用户输入除 'y' 以外的任何内容时,console.log("executes") 代码段运行且程序终止。

我对异步 JavaScript(以及一般 JavaScript)相当陌生,因此请随时批评我可能未使用的任何“最佳实践”,并指出导致上述问题的任何逻辑错误。

提前致谢!

0 个答案:

没有答案