[英]Node.js Readline Pause Code
抱歉,我剛剛開始使用JavaScript,目前正在嘗試從控制台收集用戶輸入。 我有一個看起來像這樣的代碼:
main = () => {
var num = getInput();
console.log(num);
}
getInput = () => {
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Lemme test: ', (ans) => {
rl.close();
return ans;
});
}
main();
因此,如果我嘗試運行此命令,它將顯示:
Lemme test: undefined
然后等我輸入。 顯然console.log(num);
在getInput();
之前運行getInput();
完成,或getInput();
吐出一個undefined
然后要求輸入。
BTW切換rl.close();
並return ans;
不起作用。
為什么會這樣?
發生這種情況是因為Node不等待readline獲得輸入-就像Node中的幾乎所有內容一樣,它是異步的。 因此,它會觸發用戶輸入請求,並繼續執行該程序。 一旦有用戶輸入,如果觸發您提供的回調。 因此,要解決此問題,您需要管理回調中的use輸入或具有在回調中調用的函數以異步處理輸入。 例如:
main = () => {
var num = getInput();
}
dealWithInput = (str) => {
console.log(str)
}
getInput = () => {
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Lemme test: ', (ans) => {
rl.close();
dealWithInput(ans);
});
}
main();
這是因為getInput
函數是一個回調,這意味着它將在將來的某個時刻執行,因此不是回調的console.log
會在之前執行。
當您將一個函數或方法分配給另一個函數時,它就是一個回調:
let example = () => {
// This is a callback
}
doSomething(result => {
// This is a callback too because its the same as doing the following
})
doSomething(function(result){
// This is a callback without arrow functions
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.