javascript - 在 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 ?这段代码可能工作正常,但我想学习,所以我认为它有一些问题并且可能是错误的。
如果能帮助我纠正我的错误,我将不胜感激。
解决方案
我是否以正确的方式使用 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 */
})
推荐阅读
- amazon-web-services - 我们可以使用 S3FS 挂载已经包含一些文件和目录的 s3 存储桶吗?
- android - Kotlin - 如何在 Handler 中传递一个 Runnable
- python-3.x - 如何删除 python tkinter 中的递归错误?
- r - 嵌套的 for 循环仅显示最后一次迭代
- c++ - 通过引用重载数组中的下标运算符
- shopify - 如何使用 Shopify BuyButton.js 为特定产品变体创建立即购买按钮
- javascript - 错误类型错误:尝试在 Angular 中列出 FormGroup 的 FormArray 时无法读取未定义的属性“无效”
- javascript - 手风琴恢复默认 - 仅限 JavaScript
- php - 在子数组中搜索
- haskell - Haskell:对函数列表参数中的每个元素执行函数