readline 차단되지 않은 동작 차단
readline 표준 모듈에 '차단 해제'동작이 있기 때문에이 코드가 실행되지 않는다는 것을 알았으므로 콘솔에서 세 가지 질문에 대한 답변이 있다고 상상해보십시오. 각 rl.question은 독립적 인 스레드 이므로이 코드는 실행되지 않습니다.
'use strict';
var questionaire=[['First Question: ',''],['Second Question: ',''],['Third Question: ','']];
function askaquestion(question) {
const readline = require('readline');
const rl = readline.createInterface(
{input: process.stdin, output:process.stdout}
);
rl.question(question[0], function(answer) {
console.log(answer);
question[1] = answer;
rl.close();
});
};
var i=0;
for (i=0; i < questionaire.length; i++) {
askaquestion(questionaire[i]);
}
console.log('Results:',questionaire );
출력을 실행 :
node test.js
Third Question: Results: [ [ 'First Question: ', '' ],
[ 'Second Question: ', '' ],
[ 'Third Question: ', '' ] ] <--- the last question remain unoverwritten and then the final line of the program is shown as the threads were running waiting for answers (see below)
aaa <--- I responded with a single 'a' that was sweeped by 3 running threads
a <--- Response of one thread
a <--- Response of another thread
a <--- Response of another thread (there is no order on threads exit)
제안 된 솔루션은 이벤트 이미 터를 사용하여 차단 해제 스레드의 끝을 알리고 루프 로직과 프로그램 끝을 해당 리스너 함수에 포함시킵니다.
'use strict';
var questionaire=[['First Question: ',''],['Second Question: ',''],['Third Question: ','']];
// Introduce EventEmitter object
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {};
const myEmitter = new MyEmitter();
myEmitter.on('continue', () => {
console.log('continue...');
i++; if (i< questionaire.length) askaquestion(questionaire[i],myEmitter); // add here relevant loop logic
else console.log('end of loop!\nResults:',questionaire );
});
//
function askaquestion(p_question,p_my_Emitter) { // add a parameter to include my_Emitter
const readline = require('readline');
const rl = readline.createInterface(
{input: process.stdin, output:process.stdout}
);
rl.question(p_question[0], function(answer) {
console.log(answer);
p_question[1] = answer;
rl.close();
myEmitter.emit('continue'); // Emit 'continue' event after the question was responded (detect end of unblocking thread)
});
};
/*var i=0;
for (i=0; i < questionaire.length; i++) {
askaquestion(questionaire[i],myEmitter);
}*/
var i=0;
askaquestion(questionaire[0],myEmitter); // entry point to the blocking loop
// console.log('Results:',questionaire ) <- moved to the truly end of the program
출력을 실행 :
node test2.js
First Question: 1
1
continue...
Second Question: 2
2
continue...
Third Question: 3
3
continue...
done!
Results: [ [ 'First Question: ', '1' ],
[ 'Second Question: ', '2' ],
[ 'Third Question: ', '3' ] ]
rl
당신이 readline 을 의미 한다고 가정 합니까?