重复提示用户,直到使用nodeJS async-awaitparsing为止
我试着重复地向用户询问问题,直到他们用这个代码给出了正确的答案。
问题是,如果用户没有在第一时间给出正确的答案,它不会解决。
var readline = require('readline'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); function promptAge() { return new Promise(function(resolve){ rl.question('How old are you? ', function(answer) { age = parseInt(answer); if (age > 0) { resolve(age); } else { promptAge(); } }); }); } (async function start() { var userAge = await promptAge(); console.log('USER AGE: ' + userAge); process.exit(); })();
这里是每个条件的terminal输出:
当用户第一次给出正确的答案时,它是好的…
How old are you? 14 USER AGE: 14
当用户给出了错误的答案它被卡住(不会解决,进程将不会退出)…
How old are you? asd How old are you? 12 _
当用户没有给出任何答案时,它也被卡住了…
How old are you? How old are you? How old are you? 12 _
任何人都可以解释发生了什么事情,或者给我提供一个解释这种性质的文章/video吗?
顺便说一句,我试图做到这一点使用asynchronous/等待学习目的(试图学习如何做asynchronous事情)。 我已经试过这个没有asynchronous/ await(promptAge()不返回任何承诺),这是好的。
感谢您的关注。
这与parseInt()
无关,虽然skellertorbuild议良好的做法。
问题在于,每次调用promptAge()
时都会生成一个新的Promise,但是原来的调用者即start()
只能看到第一个Promise。 如果input的是错误的input,则promptAge()
生成一个新的Promise(在永不解决的Promise中),并且您的成功代码将永远不会运行。
要解决这个问题,只能生成一个Promise。 有更多的优雅的方式来做到这一点,但为了清晰起见,并避免黑客代码变成无法识别的东西…
var readline = require('readline'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); // the only changes are in promptAge() // an internal function executes the asking, without generating a new Promise function promptAge() { return new Promise(function(resolve, reject) { var ask = function() { rl.question('How old are you? ', function(answer) { age = parseInt(answer); if (age > 0) { // internal ask() function still has access to resolve() from parent scope resolve(age, reject); } else { // calling ask again won't create a new Promise - only one is ever created and only resolves on success ask(); } }); }; ask(); }); } (async function start() { var userAge = await promptAge(); console.log('USER AGE: ' + userAge); process.exit(); })();
它看起来像你的parseInt()
函数。 在这两种情况下,您都传递一个非Number值。 首先检查它是否是一个数字,然后parsing为一个int。