I cannot for the life of me wrap my head around what I am doing wrong with this Async/Await concept. Here is my Node.js code below (two separate files).
So, the console.log("hasInvoiceAlreadyBeenPaid:", hasInvoiceAlreadyBeenPaid);
line runs before the controller.checkIfAuthNetChargedInvoice()
has been completed and shows that hasInvoiceAlreadyBeenPaid
has a value of undefined.
What am I doing wrong with this code? It’s an Async function and I am using Await, so am super confused wrapping my head around this. I should mention that the checkIfAuthNetChargedInvoice
function runs successfully but right after the console.log("🎨 ~ ctrl:", ctrl);
line shows in the logs, the console.log: hasInvoiceAlreadyBeenPaid: undefined;
appears in the logs right after that. Then the remainder of checkIfAuthNetChargedInvoiceruns
successfully. I know this is just a misunderstanding of async/await but what the heck am I doing wrong?
execute.js
const controller = require("./controller");
const hasInvoiceAlreadyBeenPaid = await controller.checkIfAuthNetChargedInvoice(
lastUnpaidSubscriptionInvoice,
authorizeNetProfileId,
);
console.log("hasInvoiceAlreadyBeenPaid:", hasInvoiceAlreadyBeenPaid);
if (hasInvoiceAlreadyBeenPaid) {
console.log("🎉 INVOICE ALREADY PAID! ");
}
--
controller.js
exports.checkIfAuthNetChargedInvoice = async (invoice, customerProfileId) => {
try {
const invoiceString = invoice._id.toString();
const authNetInvoiceNumber = invoiceString.slice(-12);
var merchantAuthenticationType =
new ApiContracts.MerchantAuthenticationType();
merchantAuthenticationType.setName(authorizeNetAPILoginKey);
merchantAuthenticationType.setTransactionKey(authorizeNetTransactionKey);
var paging = new ApiContracts.Paging();
paging.setLimit(100);
paging.setOffset(1);
var sorting = new ApiContracts.TransactionListSorting();
sorting.setOrderBy(ApiContracts.TransactionListOrderFieldEnum.ID);
sorting.setOrderDescending(true);
var getRequest = new ApiContracts.GetTransactionListForCustomerRequest();
getRequest.setMerchantAuthentication(merchantAuthenticationType);
getRequest.setCustomerProfileId(customerProfileId);
getRequest.setPaging(paging);
getRequest.setSorting(sorting);
var ctrl = new ApiControllers.GetTransactionListForCustomerController(
getRequest.getJSON(),
);
console.log("🎨 ~ ctrl:", ctrl);
ctrl.execute(async function () {
var apiResponse = ctrl.getResponse();
console.log("🎨 ~ apiResponse:", apiResponse);
var response = new ApiContracts.GetTransactionListResponse(apiResponse);
console.log(JSON.stringify(response, null, 2));
if (response != null) {
if (
response.getMessages().getResultCode() ==
ApiContracts.MessageTypeEnum.OK
) {
console.log(
"Message Code : " +
response.getMessages().getMessage()[0].getCode(),
);
console.log(
"Message Text : " +
response.getMessages().getMessage()[0].getText(),
);
if (response.getTransactions() != null) {
var transactions = response.getTransactions().getTransaction();
for (var i = 0; i < transactions.length; i++) {
const transaction = transactions[i];
const transactionId = transaction.getTransId();
const transactionStatus = transaction.getTransactionStatus();
const settleAmount = transaction.getSettleAmount();
if (
transaction.invoiceNumber == authNetInvoiceNumber &&
transactionStatus === "settledSuccessfully"
) {
invoice.status = "paid";
await invoice.save();
return true;
}
}
}
} else {
const newErrorLog = new ErrorLog({ error });
await newErrorLog.save();
}
} else {
let errorText = "checkIfAuthNetChargedInvoice: Null Response ";
if (invoice._id) {
errorText =
"checkIfAuthNetChargedInvoice: Null Response for Invoice: " +
invoice._id;
}
const newErrorLog = new ErrorLog({ error: errorText });
await newErrorLog.save();
}
});
} catch (error) {
console.log("error", error);
const newErrorLog = new ErrorLog({ error });
await newErrorLog.save();
}
};
2
Answers
Global
await
only works in ES module so you can wrap it in aasync
function then call it.try updating the function where you return promise