[英]Using generators to wait for input before continuing the body of a forEach loop
無論我閱讀多少個發電機文章,我都無法弄清楚……我也嘗試安裝所有光纖庫,但它們都不會安裝在我的機器上,但這沒關系,因為我應該學習如何無論如何,本機ES5機制仍然有效。
到目前為止,這就是我的代碼。
var arr = [1, 2, 3];
arr.forEach(function(n, i, arr){
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter input [' + [n, i].join(' ') + ']:', function(answer) {
arr[i] = { prompt: [n, i], response: answer };
rl.close();
});
});
問題在於,排序可以預期地是這樣的:
Enter input [1 0]:
Enter input [2 1]:
Enter input [3 2]:
<input>
<input>
<input>
而我需要每個輸出都直接跟在其對應的輸入之后。 如何在發電機和yield
做到這一點?
謝謝..
用試試這個--harmony
--use_strict
最新的節點(我試過v0.11.9)上:
var readline = require('readline');
function* questionaire(arr) {
for( var i = 0; i < arr.length; i++)
{
var n = arr[i];
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter input [' + [n, i].join(' ') + ']:', function(answer) {
arr[i] = { prompt: [n, i], response: answer };
rl.close();
console.log(arr);
run.next();
});
yield n;
}
}
let arr = [1, 2, 3];
var run = questionaire(arr);
run.next();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.