javascript - 如何修复 - 等待不等待
问题描述
当我运行异步函数时,我想使用不在“then”内的等待声明,但喜欢:
const todayTotalVisitor = await getLastDayVisitors();
这样,等待就不会等待。
async function sumMonth() {
const today = new Date();
if (today.getDate() == 1) return 0;
else {
const todayTotalVisitor = await getLastDayVisitors();
//query - last yestardy
Counter.find({date: {$gte: beforeYesterday, $lt:yesterday
}}).then((result1) => {
//get the totalVisitors of yestardy
const monthlyYestardy = result1[0].monthly;
//get today total visitor
return todayTotalVisitor + monthlyYestardy;
}).catch((err) => {
console.log(err);
});
}}
这样今天TotalVisitor 是未定义的。
getLastDay 访客:
async function getLastDayVisitors() {
//query - last yestardy
Counter.find({date: {$gte: beforeYesterday, $lt:yesterday
}}).then((result1) => {
//get the totalVisitors of yestardy
const TotalVisitorYesterday = result1[0].totalVisitors;
//query - general
Counter.find({name: 'general' }).then((result2) => {
//get the totalVisitors overall
const TotalVisitorOverAll = result2[0].totalVisitors;
//return the delta
return ( TotalVisitorOverAll-TotalVisitorYesterday);
}).catch((err) => {
console.log(err);
});
}).catch((err) => {
console.log(err);
});
}
谢谢你。
解决方案
您的 getLastDayVisitor 没有返回任何内容,也没有等待任何内容,因此承诺undefined
立即解析为无需等待任何异步完成
将 getLastDayVisitor 更改为使用 await,因为它已经是异步的
其他更改纯粹是在 async 中使用 await 而不是 await 和 .then - 使用其中一个
async function getLastDayVisitors() {
const result1 = await Counter.find({date: {$gte: beforeYesterday, $lt:yesterday }});
//get the totalVisitors of yestardy
const TotalVisitorYesterday = result1[0].totalVisitors;
//query - general
const result2 = await Counter.find({name: 'general' })
//get the totalVisitors overall
const TotalVisitorOverAll = result2[0].totalVisitors;
//return the delta
return ( TotalVisitorOverAll-TotalVisitorYesterday);
}
也重写sumMonth
,因为它async
太
async function sumMonth() {
const today = new Date();
if (today.getDate() == 1) return 0;
const todayTotalVisitor = await getLastDayVisitors();
//query - last yestardy
const result1 = await Counter.find({date: {$gte: beforeYesterday, $lt:yesterday }})
//get the totalVisitors of yestardy
const monthlyYestardy = result1[0].monthly;
//get today total visitor
return todayTotalVisitor + monthlyYestardy;
}
注意,我已经删除了错误处理,因为你有它可能会导致比修复更多的问题!
使用 sumMonth 之类的
sumMonth()
.then(result => doSomethingWitf(result))
.catch(err => handleTheError(err));
或者如果在异步函数中使用它
try {
result = await sumMonth();
// do something with it
} catch(err) {
// handle err here
}
推荐阅读
- azure - 使用 terraform 的 Azure API 管理器
- bash - 在同一文件夹中的 txt 文件中使用日志和参数进行卷曲
- java - 如何使用 Java Selenium 获取每个测试步骤的状态?我想知道测试步骤是通过、失败还是跳过
- typescript - NestJS Passport Linkedin 策略
- react-native - 如何使用 Formik + Yup 跳过对表单中不存在的字段的验证?
- c# - NewtonSoft.json 是第三方库吗?
- ruby-on-rails - 创建订单后如何使用 invoice_rows 设置发票?
- php - 我们可以从 URL 动态获取 php 值到批处理文件吗?
- c# - 快速排序比普通的交互排序慢?
- c - 为什么我的 C 程序可以在“git bash”中运行,但不能在“cmd”中运行?