Node.Js code returns [object Promise] when I try to send output data

Viewed 57

I have some code from a node.js server that I am trying to send to a front end app. When I display the code in the console it displays fine but when I try to send the data to the front end it just comes out as [Object Promise]. On the app.get function I want to be able to send the data out without it displaying as a promise. Can anyone help to make this data output the way I want it to?

async function refresh() {
  if (await h1.isOnline()) {
    console.log(
      "T1 : " + (await t1.get_currentValue()) + (await t1.get_unit())
    );

    console.log(
      "H1    : " + (await h1.get_currentValue()) + (await h1.get_unit())
    );
    console.log(
      "P1   : " + (await p1.get_currentValue()) + (await p1.get_unit())
    );
  } else {
    console.log("Module not connected");
  }
  setTimeout(refresh, 500);
}

startDemo();

app.get("/", function (req, res) {
  res.send("T1: " + t1.get_currentValue());
});

let port = process.env.PORT;
if (port == null || port == "") {
  port = 4000;
}
1 Answers

I assume from your other examples that t1.get_currentValue() returns a promise. As such, you have to use either await or .then() to get the value from that promise and make sure to handle rejections too:

app.get("/", async function(req, res) {
    try {
        res.send('T1: '+ await t1.get_currentValue());
    } catch(e) {
        console.log(e);
        res.sendStatus(500);
    }
});

or:

app.get("/", function(req, res) {
    t1.get_currentValue().then(val => {
        res.send('T1: '+ val);
    }).catch(e => {
        console.log(e);
        res.sendStatus(500);
    })
});
Related