promise实现猜数字游戏
时间: 2023-08-12 15:58:08 浏览: 55
下面是使用 Promise 实现的猜数字游戏的示例代码:
```javascript
function guessNumberGame() {
const randomNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
return new Promise((resolve, reject) => {
function makeGuess() {
attempts++;
const guess = parseInt(prompt("猜一个1到100之间的数字:"));
if (isNaN(guess)) {
reject(new Error("输入的不是有效数字,请重新输入。"));
return;
}
if (guess < randomNumber) {
console.log("猜的数字太小了!再试一次。");
makeGuess();
} else if (guess > randomNumber) {
console.log("猜的数字太大了!再试一次。");
makeGuess();
} else {
resolve(`恭喜!你猜对了!数字是${randomNumber},你用了${attempts}次尝试。`);
}
}
makeGuess();
});
}
guessNumberGame()
.then((message) => console.log(message))
.catch((error) => console.log(error.message));
```
上述代码中,我们使用 Promise 来封装猜数字游戏的逻辑。首先生成一个随机数 `randomNumber`,然后使用递归函数 `makeGuess` 来获取用户的猜测,并根据猜测与随机数的大小关系给出提示,直到猜对为止。
如果用户输入的不是有效数字,我们会 reject 一个带有错误信息的 Promise。如果用户猜对了数字,我们会 resolve 一个带有成功信息的 Promise。
最后,我们通过 `.then()` 来处理成功的结果,通过 `.catch()` 来处理错误的结果。