首页 > 解决方案 > 在 js 和 nodejs 中处理异步等待和承诺有一些问题

问题描述

我在我的 nodejs 应用程序中使用这种代码和平:

// some codes before this part 
// .....

// should check if user has enough balance to invest in this project
// first get user balance then multiply purchase amount to valpershare of project
let usersBalance = async () => {
  return await axios
    .post(`http://localhost:${financePort}/finance/getBalance`, {
      userId: userId,
    })
    .then((resposn) => {
      return resposn.result; // give balance -> resposn.result = balance
    });
};

let totalCost = project.valPerShare * purchaseAmount;

// now check if users balance is low than total cost then return fail
if (usersBalance < totalCost) {
  console.log(
    "users balance is not enough to invest in project , first should deposit balance "
  );
  let response = {
    status: 400,
    msg:
      "users balance is not enough to invest in project , first should deposit balance",
    result: null,
  };
  res.json(response);
  return; // it means failure 
}
// .....
// .....
// and other codes after these that depends on the results of these codes 

在这里,我尝试以异步方式从数据库获取用户的余额,并根据他的余额决定继续或显示失败,所以我向财务 api 发出请求以查询财务数据库并获取余额,然后将其值与总成本进行比较。

我的问题是这个代码对吗?我是否以正确的方式使用 async/await ?这段代码可能工作正常,但我想学习,所以我认为它有一些问题并且可能是错误的。

如果能帮助我纠正我的错误,我将不胜感激。

标签: javascriptnode.jsmongodbasynchronousasync-await

解决方案


我是否以正确的方式使用 async/await ?

恕我直言,你没有。

let usersBalance = async () => { ... 创建一个名为usersBalance.

您必须调用该函数

  • let balance = await usersBalance()或者
  • usersBalance.then( balance => { /* do something with the balance from axios */ }

让你的路由处理程序成为异步函数可能是最简单的......

route.get('balance', async function (req, res, next) {
    let totalCost = project.valPerShare * purchaseAmount;
    // now check if users balance is low than total cost then return fail
    let currentBalance = await usersBalance();
    if (currentBalance < totalCost) {
       console.error("whatever");
       let response = {
              status: 400,
              msg: "whatever",
              result: null,
       };
       res.json(response);
    }
    else { /* whatever you do on success */
})

推荐阅读