首页 > 解决方案 > 如何修复 - 等待不等待

问题描述

当我运行异步函数时,我想使用不在“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);
});
}

谢谢你。

标签: javascriptmongodbpromiseasync-await

解决方案


您的 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
}

推荐阅读