2014-02-11 90 views
1

我沒能獲得預期的結果,而是其結果是非常混亂..也許一些回調魔法或某些異步會做魔術在這裏......以上循環的NodeJS混亂

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 

回答

1

您沒有聲明command,所以node.js假設它是一個全局變量,並且每次調用message()時都會寫入該全局變量。要修復它,請使用var

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

非常感謝你!過去兩天我一直在爲此撓頭:p – Rohit