Make GET request inside for loop

本文探讨了如何使用Promise解决JavaScript中异步请求导致的结果打印为空的问题,并提供了两种实现方式:并行请求和顺序请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

share improve this question

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);
share improve this answer







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?

share improve this question
 

2 Answers

up vote 0 down vote accepted

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?

share improve this question
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值