【问题标题】:Why does Node style error 1st callback return undefined after callback为什么节点样式错误第一个回调在回调后返回未定义
【发布时间】:2020-04-05 03:43:59
【问题描述】:

当我尝试执行错误、回调功能时,以下代码返回未定义。我不明白为什么 json 没有返回,因为控制台日志输出了完整的查询。

这是将 json 生成到日志中的调用函数。


exports.getThem = (req) => {
    var addy = req.body.email;

    Picks.findOne({ 'email' :  addy }, (err, theResults) => {
        if (err) {
            return ({ 'msg': err });
        } 


        console.log("made the query " + JSON.stringify(theResults)); 
        return theResults;
    });
}; 

在上面,结果打印“进行了查询”和一个完整的 JSON 字符串。

调用代码将执行以下 JSON 并将其返回给 Postman,但不包含 theResults JSON。

console.log "log this" 永远不会执行,第二个 log 打印 "after the log" undefined。


{
  "token" : someCrazyLookingToken 
}

exports.loginUser = (req, res) => {

         var theResults;

          theResults = Picks.getPicks( req ,  ( err , thePicks)  => {
                    console.log("log this" + JSON.stringify(thePicks));                    
                    if (!err){
                        console.log ("what happened" + err)
                    }
         });
         console.log("after the call " + JSON.stringify(theResults));                    
         return res.status(200).json({  picks: thePicks, token: createToken(user) });
}

为什么?回调中是否存在我没​​有等待的时间问题?

【问题讨论】:

标签: javascript node.js express


【解决方案1】:

这不一定是时间问题,而可能是您对回调如何工作的误解,尤其是在它们的范围内。在您的代码中,theResults 永远不会有值。

尝试像这样设置它,并阅读承诺和回调以更好地理解两者。

exports.loginUser = async (req, res) => {
    try {
        const theResults = await new Promise((resolve, reject) => {
            Picks.getPicks(req, (err, thePicks) => {
                if (err) {
                    return reject(err);
                }
                return resolve(thePicks);
            })
        });

        return res.status(200).json({picks: theResults, token: createToken(user)});
    } catch (err) {
        //handle err
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多