我是node.js的新手,所以请耐心等待:)
我需要做什么:
我做错了什么?
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
中没有任何内容正在执行,为什么?
答案 0 :(得分:0)
我认为你需要像async这样的东西 请检查此答案:simplest-way-to-wait-some-asynchronous-tasks-complete-in-javascript
答案 1 :(得分:0)
status
和data
中没有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代码。