I am trying to make a call to four API endpoints using Nodejs in a synchronous method. I have seen (and tried!) many modifications of examples on stack overflow where this can be done using Promises and 'async'. But, the problem that I am having is that I specifically need the endpoint to retrieve a value to me before I call the next API so that I can concatenate that returned value into my next API call.
Here is the code I am working on:
var STATE = 'Kansas';
var OCCUPATION_NAME = 'Farmers';
getReq('http://api.dol.gov/V1/Statistics/OES/OE_AREA/?KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&$filter=AREA_NAME eq ' + STATE).then(function(body1){
var options = {
host: 'api.dol.gov',
path: encode,
type: 'GET',
dataType: 'json',
headers: {'accept' : 'application/json'}
};
var x = http.request(options,function(res){
console.log("Connected");
var str = '';
res.on('data', function(chunk) {
str += chunk;
});
res.on('data',function(data){
if(res.statusCode == 200){
try{
var data = JSON.parse(str);
var state = data.d[0].AREA_CODE;
array.push(state);
console.log(state);
}catch(e){
console.log('Error parsing JSON');
}
}
//console.log(data.toString());
});
});
x.end();
return getReq('http://api.dol.gov/V1/Statistics/OES/OE_OCCUPATION/?KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&$filter=OCCUPATION_NAME eq ' + OCCUP);
}).then(function(body2){
var options = {
host: 'api.dol.gov',
path: encode,
type: 'GET',
dataType: 'json',
headers: {'accept' : 'application/json'}
};
var x = http.request(options,function(res){
var str = '';
res.on('data', function(chunk) {
str += chunk;
});
res.on('data',function(data){
if(res.statusCode == 200){
try{
var data = JSON.parse(str);
var occupationNum = data.d.results[0].OCCUPATION_CODE;
array.push(occupationNum);
console.log(occupationNum);
}catch(e){
console.log('Error parsing JSON');
}
}
});
});
x.end();
return getReq('http://api.dol.gov/V1/Statistics/OES/OE_SERIES/?KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&$filter=(OCCUPATION_CODE eq ' + "'" + occupationNum + "'" + ') and (AREA_CODE eq ' + "'" + areaCode + "'" + ')');
}).then(function(body3){
var options = {
host: 'api.dol.gov',
path: encode,
type: 'GET',
dataType: 'json',
headers: {'accept' : 'application/json'}
};
var x = http.request(options,function(res){
console.log("Connected");
var str = '';
res.on('data', function(chunk) {
str += chunk;
});
res.on('data',function(data){
if(res.statusCode == 200){
try{
var dataA = JSON.parse(str);
//run a for loop
for(var i = 0; i < dataA.d.length; i++){
var seriesNum = dataA.d[i].SERIES_ID;
array.push(seriesNum);
console.log(seriesNum);
}
//end for
}catch(e){
//console.log('Error parsing JSON');
}
}
});
});
x.end();
});
Notice how in my last endpoint call, it takes in the results from my first and second endpoint calls. Any help would be appreciated.
via learningToCode
No comments:
Post a Comment