提问者:小点点

从presenter方法中执行的函数返回json对象


我需要将json对象从匿名函数加载到变量实例。

本例中的实例未定义。

我敢肯定,解决方法很简单,但是新手在节点上找不到答案…:(

module.exports = {
    create: function(req,res){
        instance = EngineInstance.findById(req.body.engineInstanceId).exec(function(err,instance){
            if (err) return res.send(err,500);
            if (!instance) return res.send("No engine instance found!", 404);
            return instance;
        });
        namespamce = instance.namespace;...
    }
};

共2个答案

匿名用户

对于异步代码的工作方式,您有一个非常常见和基本的误解。句号。去读教程,做有指导的练习。异步IO(如前面的findbyid)使用回调来调用带有结果变量的函数。它不使用返回值,因为由于异步代码执行的顺序,返回值是无用的。

module.exports = {
    create: function(req,res){
        instance = EngineInstance.findById(req.body.engineInstanceId).exec(function(err,instance){
            if (err) return res.send(err,500);
            if (!instance) return res.send("No engine instance found!", 404);
            //it is useless to return a value from this anonymous async callback
            //nothing will receive it. It will be ignored.
            //probably something like this is what you need
            req.namespamce = instance.namespace;
        });
        //do NOT put code here that needs req.namespace. This code runs BEFORE
        //the `findById` I/O callback runs.
    }
};

匿名用户

将MYSQL查询更改为一并查询多个内容,而不是隔离对accessPoint的查询,并添加了以下代码:

results[0].accessPoint = JSON.parse(results[0].accessPoint)
res.send(results[0]);

现在我拿回了这个,这正是我想要的:

"accessPoint": {
    "mode": "client",
    "rate": 0,
    "ssid": "RMG",
    "signal": 0,
    "channel": 0,
    "password": "",
    "username": "example@aol.com"
  }