[英]Repeatedly prompt user until resolved using nodeJS async-await
我嘗試向用戶重復詢問問題,直到他們使用此代碼給出正確的答案。
問題是,如果用戶第一次沒有給出正確的答案,它將無法解決。
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();
})();
以下是每種情況的終端輸出:
當用戶第一次給出正確答案時,它很好......
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
_
任何人都可以解釋發生的事情,或者給我一些解釋這種性質的文章/視頻嗎?
順便說一下,我嘗試使用async / await進行學習(嘗試學習如何異步處理)。 我已經嘗試過沒有async / await(promptAge()不返回任何承諾)並且沒關系。
感謝您的關注。
它與parseInt()
無關,盡管skellertor建議良好實踐。
問題是你每次調用promptAge()
時都會生成一個新的Promise - 但是原始調用者ie start()
只能看到第一個Promise。 如果輸入錯誤的輸入, 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值。 首先檢查它是否是一個數字,然后再將其解析為int。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.