Nodejs循环混乱

时间:2014-02-11 09:18:30

标签: javascript node.js asynchronous

我无法获得预期的结果而是结果非常令人困惑..也许一些回调魔法或某些异步会在这里做魔术......

app.post('/upload', function (req, res) {
  var phone_add = req.body.phone_add;
  whatsapp = phone_add.split(',');
  var i=0;

  for (i=0;i<whatsapp.length;i++) {
    message(whatsapp[i],i);
  }
});

function message(whatsapp,i) {
  var mess = "\"Test automation\"";

  console.log(whatsapp);
  command = "yowsup-cli.py -s " +whatsapp+" "+mess+" -c config.txt";

  child = exec(command,function (error, stdout, stderr) {
    if (error !== null) {
      console.log('exec error: ' + error);
      console.log(command);
    }
    else
      console.log("Success! "+i+"  "+command);
  });
}

上述输出 - &gt;

919999999999

919222222222

919111111111

Success! 2  yowsup-cli.py -s 919111111111 "Test automation" -c config.txt

Success! 0  yowsup-cli.py -s 919111111111 "Test automation" -c config.txt

Success! 1  yowsup-cli.py -s 919111111111 "Test automation" -c config.txt

而我的预期输出 - >

919999999999

919222222222

919111111111

Success! 2  yowsup-cli.py -s 919999999999 "Test automation" -c config.txt

Success! 0  yowsup-cli.py -s 919222222222 "Test automation" -c config.txt

Success! 1  yowsup-cli.py -s 919111111111 "Test automation" -c config.txt

1 个答案:

答案 0 :(得分:1)

您没有声明command,因此node.js假定它是一个全局变量,并且每次调用message()时它都会写入该全局变量。要解决此问题,请使用var

var command = "yowsup-cli.py -s " +whatsapp+" "+mess+" -c config.txt";
//^ add var keyword