javascript - HTTP.post() callback in loop -


i've got loop of http.post() on meteor server:

for (var = 0; < smsmessages.length; i++) {     http.post("https://smsapiaddress/sms.do", smsmesseges[i], function(error, result) {         if (error) {             seterrorindatabase(smsmessages[i]);         }         if (result) {             setresultindatabase(smsmessages[i]);         }     }); 

how can pass proper smsmessages[i] callback function?

as http request asynchronous value of i shared requests. use closures inside for loop. keep separate copy of i each iteration.

see comments highlighted in code:

for (var = 0; < smsmessages.length; i++) {      (function(i) {     // ^^^^^^^^^^^         http.post("https://smsapiaddress/sms.do", smsmessages[i], function(error, result) {             if (error) {                 seterrorindatabase(smsmessages[i]);             }             if (result) {                 setresultindatabase(smsmessages[i]);             }         });     }(i)); // call function current value of     // ^^^ } 

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -