即使实现了 Async/Await,Node.js 功能也能部分完成

问题描述 投票:0回答:1

我一生都无法思考我在异步/等待概念上做错了什么。下面是我的 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();
  }
};
javascript node.js async-await
1个回答
0
投票

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();
© www.soinside.com 2019 - 2024. All rights reserved.