简体   繁体   English

尝试将await函数的返回值设置为常量时接收到undefined

[英]Receiving undefined when trying to set return value of await function as a constant

I'm trying to set a constant to an await function to get the return information from getInfo. 我试图为await函数设置一个常量,以从getInfo获取返回信息。 I can console long the object before returning it. 我可以在返回对象之前先对其进行较长的操作。 But when I try to console log the value in post I get undefined. 但是,当我尝试控制台日志中的值后,我变得不确定。 What am I doing wrong? 我究竟做错了什么?

router.post('/', function(req,res,next) {
    (async function(){
        const modifierInfo = await getInfo();
            console.log("returns undefined", modifierInfo)
            //do more with return info after
    })().catch(next)
});

const getInfo = () => {
    (async function(){
        try {
            const ps = new sql.PreparedStatement(pool);
            const statement = await ps.prepare("selectQuery");
            const result = await statement.execute();
            const modifierInfo = await result.recordset[0];
            await statement.unprepare();
            console.log("returns object", modifierInfo)
            return modifierInfo;
        } catch (err) {
            console.log(err)
        }
    })()
};

I think the issue is that getInfo itself needs to by async. 我认为问题在于getInfo本身需要异步处理。 try something like this: 尝试这样的事情:

router.post('/', async (req,res,next) => {
    try {
        const modifierInfo = await getInfo(req.body.groupID);
        console.log(modifierInfo)
    } catch(err) {
        console.log(err)
    }
});

async function getInfo(groupID) {
    try {
        const ps = new sql.PreparedStatement(pool);
        const statement = await ps.prepare("selectQuery");
        const result = await statement.execute();
        const modifierInfo = await result.recordset[0];
        await statement.unprepare();
        console.log("returns object", modifierInfo)
        return modifierInfo;
    } catch (err) {
        console.log(err)
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM