Node.js - 加载数据,然后点击网址 - 异步

时间:2016-01-25 12:35:19

标签: javascript node.js asynchronous foreach

我是node.js的新手,所以请耐心等待:)

我需要做什么:

  • 从用户网址
  • 加载
  • 为每个ID点击另一个网址

我做错了什么?

var http = require('http');
var Client = require('node-rest-client').Client;

var client = new Client();

url = 'http://example.com/api/get-users';

client.get(url, function (data, response) {
    if (data.status == 'OK') {
      users = data.users;

      users.forEach(function(item) {
        newUrl = 'http://example.com/generateStats/' + item;
        client.get(newUrl, function(data, response){
          console.log(data);
        });
      });
    }
});

users的值为:[1,2,4,5,7,...]

forEach中没有任何内容正在执行,为什么?

2 个答案:

答案 0 :(得分:0)

我认为你需要像async这样的东西 请检查此答案:simplest-way-to-wait-some-asynchronous-tasks-complete-in-javascript

答案 1 :(得分:0)

statusdata中没有response因此它永远不会进入if块。要处理node-rest-client的错误,您必须收听error事件:

var http = require('http');
var Client = require('node-rest-client').Client;

var client = new Client();

url = 'http://example.com/api/get-users';

client.get(url, function(data, response) {
  // if there is an error, this function is not executed
  var users = data.users;

  users.forEach(function(item) {
    newUrl = 'http://example.com/generateStats/' + item;
    client.get(newUrl, function(data, response) {
      console.log(data);
    });
  });
}).on('error', function(err) {
  console.log('something is wrong: ' + err.code);
});

虽然有response.statusCode,但它会返回类似200的http代码。