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
Post a Comment