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

时间:2019-04-10 22:57:25

标签: javascript node.js async-await

我试图为await函数设置一个常量,以从getInfo获取返回信息。我可以在返回对象之前先对其进行较长的操作。但是,当我尝试控制台日志中的值后,我变得不确定。我在做什么错了?

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)
        }
    })()
};

1 个答案:

答案 0 :(得分:2)

我认为问题在于getInfo本身需要异步处理。尝试这样的事情:

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)
    }
};