我一生都无法思考我在异步/等待概念上做错了什么。下面是我的 Node.js 代码(两个单独的文件)。
因此,
console.log("hasInvoiceAlreadyBeenPaid:", hasInvoiceAlreadyBeenPaid);
行在 controller.checkIfAuthNetChargedInvoice()
完成之前运行,并显示 hasInvoiceAlreadyBeenPaid
的值为未定义。
这段代码我做错了什么?这是一个异步函数,我正在使用 Await,所以我对此非常困惑。我应该提到
checkIfAuthNetChargedInvoice
函数成功运行,但在日志中显示 console.log("🎨 ~ ctrl:", ctrl);
行之后,console.log: hasInvoiceAlreadyBeenPaid: undefined;
立即出现在日志中。然后剩下的checkIfAuthNetChargedInvoiceruns
就成功了。我知道这只是对 async/await 的误解,但我到底做错了什么?
执行.js
const controller = require("./controller");
const hasInvoiceAlreadyBeenPaid = await controller.checkIfAuthNetChargedInvoice(
lastUnpaidSubscriptionInvoice,
authorizeNetProfileId,
);
console.log("hasInvoiceAlreadyBeenPaid:", hasInvoiceAlreadyBeenPaid);
if (hasInvoiceAlreadyBeenPaid) {
console.log("🎉 INVOICE ALREADY PAID! ");
}
--
控制器.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();
}
};
Global
await
仅适用于 ES 模块,因此您可以将其包装在 async
函数中然后调用它。
const controller = require("./controller");
async function checkInvoicePaid() {
const hasInvoiceAlreadyBeenPaid = await controller.checkIfAuthNetChargedInvoice(
lastUnpaidSubscriptionInvoice,
authorizeNetProfileId,
);
console.log("hasInvoiceAlreadyBeenPaid:", hasInvoiceAlreadyBeenPaid);
if (hasInvoiceAlreadyBeenPaid) {
console.log("🎉 INVOICE ALREADY PAID! ");
}
}
checkInvoicePaid();