首页 > 解决方案 > 直到循环中断后,异步函数才会在 while 循环中运行

问题描述

我正在为节点中的纸牌游戏编写一个简单的程序。截至目前,我只是在测试它,所以我使用 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)相当陌生,所以请随时批评我可能未使用的任何“最佳实践”,并指出导致上述问题的任何逻辑错误。

提前致谢!

标签: javascriptnode.jsapiasynchronousasync-await

解决方案


推荐阅读