Problem: I have very little experience working with async await functions and I am trying to execute a nested async await function within an if-else statement that depends on a higher level async function to execute upon an event detection. I expect to get a successful http response back from the nested async function, but I continue getting a null value for a response. The nested async function works as expected outside of the if-else statement, however. My goal is to simply be able to get the "await new Promise" part of the code to return a http response within the conditional if-else statement. Any help with this is appreciated.
What I've tried: I haven't really made any attempts to remedy the situation besides searching for questions with similar issues since I know very little about the nature of async await functions.
Code:
exports.handler = async (event) => {
const sensorId = event.sensorId;
ddb.scan(params, function (err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("Success", data);
console.log(typeof(data));
data.Items.forEach(function (item, index, array) {
console.log("printing", item);
console.log('Testing', item.sensorId.S);
if (item.sensorId.S == sensorId) {
console.log('New sensorId was not created. Already Exists.');
return ;
}
else {
// Here is the nested async await function
async () => {
console.log(event.sensorId);
const req = new AWS.HttpRequest(appsyncUrl, region);
const item = {
input: {
id: event.sensorId,
sensorId: event.sensorId
}
};
req.method = "POST";
req.path = "/graphql";
req.headers.host = endpoint;
req.headers["Content-Type"] = "application/json";
req.body = JSON.stringify({
query: print(createSensor),
operationName: "createSensor",
variables: item
});
console.log(typeof(graphqlQuery));
if (apiKey) {
req.headers["x-api-key"] = apiKey;
} else {
const signer = new AWS.Signers.V4(req, "appsync", true);
signer.addAuthorization(AWS.config.credentials, AWS.util.date.getDate());
}
const data = await new Promise((resolve, reject) => {
const httpRequest = https.request({ ...req, host: endpoint }, (result) => {
let data = "";
result.on("data", (chunk) => {
data += chunk;
});
result.on("end", () => {
resolve(JSON.parse(data.toString()));
});
});
httpRequest.write(req.body);
httpRequest.end();
});
try {
return {
statusCode: 200,
body: data
};
}
catch(err) {
console.log('error', err);
}
};
}});
}
});
Expected result:
Response
{
"statusCode": 200,
"body": {
"data": {
"createSensor": {
"id": "fd78597a-12fd-4bd1-9f9d-6ee1a88e197d",
"digit": null,
"date": null,
"timestamp": null
}
}
}
}
Actual result:
Response
null