Nodejs循环混淆

我不能得到预期的结果,而是结果是非常混乱..也许一些callback魔术或一些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 

而期望的输出由me->

 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假定它是一个全局variables,并且每次调用message()时都会写入该全局variables。 要修复它,请使用var

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