I am doing a simple exercise to understand how async.js works with node.js. The program will ask for hours worked and hourly rate and multiply them to tell the total income.
The code looks like this:
var async =require('async');
var rl = require('readline');
//variables
var horas=0;
var rate =0;
var sueldo =0;
//readline
var int=rl.createInterface({
input:process.stdin,
output:process.stdout
});
var items = [
{nombre: "worked hours", valor:horas},
{nombre:"hourly rate",valor:rate}
];
async.each(items,
function(item,callback)
{
int.question('Tell me your '+ item.nombre,function(data)
{
item.valor =Number(data);
callback(null);
});
},
function(err,results){
console.log(results);
});
I know this same thing can be achieved using realine.question(), but the point of the exercise is to understand how async.js works.
When I run this code, only the first item in the collection gets called. No matter how many times I press Enter, the second item in the items array never gets processed. I think I am missing something very basic here but have no idea what. Can someone help?
You need to use async.eachSeries instead of async.each here because you want the questions to occur one after the other instead of at the same time:
async.eachSeries(items, function(item,callback) { ... }