简体   繁体   中英

Return call is not working in Node.js with Express

My code block for crud.js is as follows,

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,

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,

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

client.connect() is asynchronous; you have no way of getting the actual return value of whatever further asynchronous code (such as client.invoke ) you call.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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