Node.js发送数据到前端返回[object Promise]问题求助
问题解决方法
问题根源
你调用的t1.get_currentValue()是异步方法,返回的是Promise对象,你没有等待异步执行完成就直接拼接返回给前端,自然会输出[object Promise]。你之前写的refresh函数因为标记了async且调用异步方法时加了await关键字等待结果返回,所以控制台打印是正常的。
修复方案
把接口的回调函数改成async异步函数,在调用异步方法前加await等待结果返回即可,修改后的代码如下:
// 给接口回调加async标记 app.get("/", async function (req, res) { // 加await等待异步方法返回实际值 res.send("T1: " + await t1.get_currentValue()); });
如果你需要和refresh函数一样返回所有传感器数据,也可以统一处理后返回结构化JSON,更方便前端解析:
app.get("/", async function (req, res) { if (await h1.isOnline()) { const t1Value = await t1.get_currentValue() const t1Unit = await t1.get_unit() const h1Value = await h1.get_currentValue() const h1Unit = await h1.get_unit() const p1Value = await p1.get_currentValue() const p1Unit = await p1.get_unit() res.json({ t1: `${t1Value}${t1Unit}`, h1: `${h1Value}${h1Unit}`, p1: `${p1Value}${p1Unit}` }) } else { res.status(503).send("Module not connected") } });
注意事项
await关键字只能在被async标记的函数内部使用- 如果多个异步请求没有依赖关系,可以用
Promise.all()批量处理,优化接口响应速度
内容的提问来源于stack exchange,提问作者Pizzaza
相关产品推荐
相关产品推荐

