http://stackoverflow.com/questions/30826474/get-request-inside-of-a-loop-in-javascript
My code:
var locations = { "testurl1" , "testurl2" }, results = [];
locations . forEach ( function ( location , index ){
request . get ( location , function ( error , response , body ){
if (! error && response . statusCode == 200 ) {
var jsonResponse = JSON . parse ( body );
results . add ( jsonResponse . address );
}
}
})
console . log ( results );
The results are printed as blank due to asynchronous get request. How can i make this work so I have all addresses in results?
Do you want all the get requests to be done at the same time or one after the other? You can do all at once with a forEach loop. forEach works better than a normal for loop because it gives you a new instance of elem
and n
in each iteration.
object . forEach ( function ( elem , n ) {
/*Other code */
$ . get (..., function ( data ){
//do stuff
});
});
But if you want to do the requests one after the other you could do it this way.
( function loop ( n ) {
if ( n >= object . length ) return ;
/*Other code */
$ . get (..., function ( data ){
//do stuff
loop ( n + 1 );
});
})( 0 );
http://stackoverflow.com/questions/31367689/make-get-request-inside-for-loop
My code:
var locations = { "testurl1" , "testurl2" }, results = [];
locations . forEach ( function ( location , index ){
request . get ( location , function ( error , response , body ){
if (! error && response . statusCode == 200 ) {
var jsonResponse = JSON . parse ( body );
results . add ( jsonResponse . address );
}
}
})
console . log ( results );
The results are printed as blank due to asynchronous get request. How can i make this work so I have all addresses in results?
Maybe promises can help in this situation. Here is my solution:
'use strict' ;
var request = require ( 'request' );
var Q = require ( 'q' );
var defer = Q . defer ();
var promise = defer . promise ;
var locations = [
'http://www.google.com' , 'http://www.instagram.com'
],
results = [];
locations . forEach ( function ( location , index ) {
request . get ( location , function ( error , response , body ) {
if (! error && parseInt ( response . statusCode ) === 200 ) {
results . push ( response . statusCode );
}
if (( locations . length - 1 ) === index ) {
defer . resolve ();
}
});
});
promise . then ( function () {
console . log ( 'RESULTS:' , results );
});
I tested this and it's working fine. Promises are briefly explained here .
My code:
var locations = { "testurl1" , "testurl2" }, results = [];
locations . forEach ( function ( location , index ){
request . get ( location , function ( error , response , body ){
if (! error && response . statusCode == 200 ) {
var jsonResponse = JSON . parse ( body );
results . add ( jsonResponse . address );
}
}
})
console . log ( results );
The results are printed as blank due to asynchronous get request. How can i make this work so I have all addresses in results?