javascript - Nodejs 循环困惑

标签 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);
  });
}

以上输出 ->

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

最佳答案

您没有声明command,因此node.js假设它是一个全局变量,并且每次您调用message()时它都会覆盖该全局变量。要修复它,请使用 var

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

关于javascript - Nodejs 循环困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21697611/

相关文章:

javascript - 自动包装任何 Node.js 回调

javascript - 如何在不使用 HTML &lt;!--[if]--> 的情况下根据浏览器版本选择 jQuery 版本

javascript - React Native - Redux 状态正在更新,但组件 View 未正确更新

c++ - Node.JS 安装 CLD

javascript - 异步等待内部如何工作?

javascript - 形成多行插入的数组格式nodejs-mysql

c# - 等待任务完成而不阻塞 UI 线程

python - 在普通函数中调用异步函数

javascript - 除非我单击页面,否则 Firefox 不会调用 `beforeunload` 事件

javascript - 检索 HTML 元素的位置 (X,Y)