Essentially the issue is that I have multiple chained promised in an async function. So obviously the code should be waiting for the response before proceeding onto the next part. However with my test case it only works properly after multiple runs. Otherwise it shows the console.log statements sequentially after each run until around 5 runs or so when the final data appears. Sorry if this is an obvious answer or my code is atrocious. I'm rather new to both NodeJS and Async functions. It should also be noted I'm using NodeJS v8.10.
The order is essentially: Call to s3 to get ID in text file -> async function to call api to verify group details -> async function to call api to get other information based on the last function etc.
I've tried messing with the order of the async functions, and searching online for anything like this phenomenon but I was unable to find any examples.
const https = require('https');
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
exports.handler = async (event, context) => {
var groupData;
var groupID;
await fetchGroupID().then(function(fetchedGroupID){
groupID = fetchedGroupID;
return fetchedGroupID;
}).then(function(data){
fetchGroupInfo().then(function(groupInfo){
groupData = groupInfo;
var fetchedGroupID = groupInfo.id;
fetchGroupEvents(fetchedGroupID).then(function(data){
console.log("Group Events: ", data);
});
});
});
console.log(groupData);
};
// Example of one of the async functions
async function fetchGroupEvents(fetchedGroupID)
{
console.log("Fetched GI: ", fetchedGroupID);
console.log("GI: ", groupID);
return new Promise((resolve, reject) => {
const options = {
protocol: 'https:',
hostname: 'api.boomset.com',
port: 443,
path: '/events?group_id=' + groupID,
method: 'GET',
headers: {
'Content-Type' : 'application/json',
'Authorization' : 'Token ****',
'Accept-Encoding': 'gzip, deflate'
}
};
const req = https.request(options, (res) => {
//console.log(`statusCode: ${res.statusCode}`);
res.setEncoding('utf8');
res.on('data', function(data) {
console.log(data);
//var jsonData = JSON.parse(data);
//console.log(jsonData);
resolve(data);
});
});
req.on('error', (error) => {
//console.error(error);
reject(error.message);
});
req.end();
});
};
Ideally this would all be completed in one run.