节点js API在控制台打印正确数据时返回空数据

时间:2017-10-30 10:59:46

标签: javascript node.js async-await

这很奇怪。我创建了一个nodejs api,它对数据进行了一些繁重的处理并返回响应。这个API的问题是,它返回空数据但是当我做控制台时,它显示正确的数据。我完全不确定为什么节点对我来说就像这样。

这是我的代码(相关代码):

app.js

app.post('/abc/cdeApi', (request, response) => {
    myController.cdeApi(request, response)
})

myController.js

    cdeApi(request, response){
            this.simpleHttpRequestHandler(request, response);
        }

simpleHttpRequestHandler(request, response){
         return (async () =>{
                console.log("Inside base controller")
                let result = await this.myService.cdeApi(request.body);
                console.log(result); // It prints correct here...
                response.status(200).json({result}); // But result goes an empty array
            }
        })();
    }

myService.js

cdeApi(body){
return (async() => {
  console.log("Inside Service")
  let rawResponse = this.myQueryHelper.cdeApi(body); // Received the raw response from DB
  let processedResponse = this.processResponse(rawResponse);
})
}

processResponse(response){
 let finalData = [] ; // I believe its returning this only, without waiting for loop below to complete
 for(i =0; i<=rawData.length; i++){
  finalData[rawData.id] = rawData.data;

 }
console.log(finalData); // Prints conrrect value
 return finalData; // return empty (initialized) value.
}

3 个答案:

答案 0 :(得分:0)

response.status(200).json({result});

应该是     response.status(200)上传.json(结果);

答案 1 :(得分:0)

您可以在控制器中以这种方式尝试

async function simpleHttpRequestHandler(request, response){

     console.log("Inside base controller")
     let result = await this.myService.cdeApi(request.body);
     console.log(result); 
     response.status(200).json({result}); 
}

我也怀疑你的代码中可能存在一个空的next()调用

答案 2 :(得分:0)

好的..所以问题是由于一个愚蠢的错误。以下是带有问题的示例代码(在myService.js中):

processResponse(response){
 let finalData = [] ; // This needed to be initialized as an object
 for(i =0; i<=rawData.length; i++){
  finalData[rawData.id] = rawData.data;

 }

我已经将finalData初始化为一个数组,但是在循环中我将finalData变量视为一个对象。记住JS没有数据类型。所以在这种情况下,JS将两者都视为不同的变量,并将其返回的finalData(初始化为数组)