大家好我试图使用从第一个api url请求收到的值作为第二个api url的参数。因此,我创建了一个for循环,并且认为对于数组中的每个元素,迭代都会将其作为参数发送(这些就像你在下面看到的变量user,language,city)
但我认为它不起作用,因为for循环是同步的,来自nodejs的模块请求是异步的。但是,我无法找到另一种方法......
request(firstUrl, function(err, res, body) {
let input = JSON.parse(body);
for( var i=0 ;i< input.length; i++){
var user= input[i]["user"]
var language= input[i]["language"]
var city= input[i]["city"]
var query_url= encodeURIComponent('{"data":{"call":{"data":[{"text":'+city+',"language":'+language+',"user":'+user+',"id":'+id+'}]}}}')
var secondUrl = {
url: `http://api.com/?request=${query_url}`,
method: 'GET',
headers: {
"Content-type": "application/json"
}
};
request(secondUrl, function(err, res, body) {
let input = JSON.parse(body);
console.log(err)
console.log(res)
console.log(input)
});
}
return mongo.multiSave(input.contents)
});
&#13;
答案 0 :(得分:1)
确实如前所述,承诺可以通过更易读的代码轻松实现。结帐request-promise。我还使用Promise.all来并行解析所有第二个请求。这是我的解决方案(我还没有测试过代码)
request(firstUrl).then(function(body) {
return JSON.parse(body);
}).then(function(input) {
return Promise.all(secondRequests(input));
}).then(function(bodies) {
bodies.forEach(function(body) {
let input = JSON.parse(body);
console.log(err)
console.log(res)
console.log(input)
})
}).catch(function (err) {
});
function secondRequests(input) {
var promises = [];
for( var i=0 ;i< input.length; i++){
var user= input[i]["user"]
var language= input[i]["language"]
var city= input[i]["city"]
var query_url= encodeURIComponent('{"data":{"call":{"data":[{"text":'+city+',"language":'+language+',"user":'+user+',"id":'+id+'}]}}}')
var secondUrl = {
url: `http://api.com/?request=${query_url}`,
method: 'GET',
headers: {
"Content-type": "application/json"
}
};
promises.push(request(secondUrl));
}
return promises;
}
答案 1 :(得分:0)
尝试使用request-promise。哪个会帮你解决
var options = {
method: 'POST',
uri: 'http://api.posttestserver.com/post',
body: {
some: 'payload'
},
json: true // Automatically stringifies the body to JSON
};
request(options).then(function (parsedBody) {
let input = JSON.parse(parsedBody);
for (var i = 0; i < input.length; i++) {
var user = input[i]["user"]
var language = input[i]["language"]
var city = input[i]["city"]
var query_url = encodeURIComponent('{"data":{"call":{"data":[{"text":' + city + ',"language":' + language + ',"user":' + user + ',"id":' + id + '}]}}}')
var secondOptions = {
url: `http://api.com/?request=${query_url}`,
method: 'GET',
headers: {
"Content-type": "application/json"
}
};
request(secondOptions).then(function (body) {
let input = JSON.parse(body);
console.log(err)
console.log(res)
console.log(input)
})
}
return mongo.multiSave(input.contents)
}).catch(function (err) {
});