简体   繁体   English

返回调用在带有 Express 的 Node.js 中不起作用

[英]Return call is not working in Node.js with Express

My code block for crud.js is as follows,我的 crud.js 代码块如下,

const listall = () => {
  return client.connect(() => {
    return client.invoke("ZSD_CP_PRICE_GET_ALL", {}, (err, res) => {
       if (err) {
         console.log('error in invoke', err);
       }
       console.log("ZSD_CP_PRICE_GET_ALL", res);
       return res;
    });
  });
}

My code block for viewpage.js is as follows,我的 viewpage.js 代码块如下,

router.get('/', function(req, res) {
  res.render('viewpage', {title: 'SAP', data: sapview.listall()})
})

module.exports = router;

My code block for viewpage.jade is as follows,我的 viewpage.jade 代码块如下,

extends layout

block content
  h1= title
  p Welcome to #{title}
  p Data #{data}

When I run the node application terminal logs the result like,当我运行节点应用程序终端时,会记录如下结果,

ZSD_CP_PRICE_GET_ALL {
  IS_RETURN: {
    TYPE: ''
}

But the res is never returned as I mentioned in "return res" after the console.log block in crud.js file但是 res 永远不会像我在 crud.js 文件中的 console.log 块之后的“返回 res”中提到的那样返回

client.connect() is asynchronous; client.connect()是异步的; you have no way of getting the actual return value of whatever further asynchronous code (such as client.invoke ) you call.您无法获得您调用的任何其他异步代码(例如client.invoke )的实际返回值。

I suggest promisifying the invocation,我建议承诺调用,

const listall = () => {
  return new Promise((resolve, reject) => {
    client.connect(() => {
      client.invoke("ZSD_CP_PRICE_GET_ALL", {}, (err, res) => {
        if (err) {
          return reject(err);
        }
        resolve(res);
      });
    });
  });
};

and then getting the data in an async function:然后在异步函数中获取数据:

router.get("/", async (req, res) => {
  const data = await sapview.listall();
  res.render("viewpage", { title: "SAP", data });
});

(A further refactoring would involve a generic promisified "invoke method" function.) (进一步的重构将涉及一个通用的承诺“调用方法”函数。)

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

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