如何使用'await'或'.then'来处理带有Logix.js的node.js express中的异步导出?"/>
我如何使用'await'或'.then'来处理带有Logix.js的node.js express中的异步导出?
我正在尝试在两个节点之间共享信息,但没有任何运气。我假设这是因为方法是异步方法,但主模式不允许我使用“等待”或“.then”谢谢!
导出价值的节点
"use-strict";
const PLC = require("node-logix").default;
PLC.defaultOptions.Micro800 = true;
const comm = new PLC("192.168.0.5");
var arr1 = [];
comm
.connect()
.catch(console.error);
comm.on("connect", () => {
console.log("PLC connected successful! ");
interval1 = setInterval(poolData, 1500);
});
comm.on("connect_error", e => {
console.log("Fail to connect PLC!");
});
comm.on("disconnect", reason => {
clearInterval(interval1);
console.log("PLC disconnected reason:", reason);
});
function poolData()
{
comm.read("SETTINGS", { count: 10 })
.then(data => {
arr1 = data.splice(0);
exports.arr1 = arr1;
//console.log(arr1);
})}
节点尝试使用它。
/*Required External Modules*/
const express = require("express");
const path = require("path");
var moduleL = require('./Logix.js');
/*App Variables*/
const app = express();
const port = process.env.PORT || "8000";
arr1 = await moduleL.arr1; // This is the issue
console.log("hey: " + arr1);
/*App Configuration*/
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
app.use(express.static(path.join(__dirname, "public")));
/*Routes Definitions*/
app.get("/", (req, res) => {
res.render("index", { title: "Home" });
});
app.get("/user", (req, res) => {
res.render("user", { title: "Profile", userProfile: arr1 });
});
/*Server Activation*/
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`);
});
尝试使用 await 然后。两者都不会真正起作用。期望节点在将其设置为变量之前等待直到导出实际值。
我也试过:
async function poolData()
{
comm.read("SETTINGS", { count: 10 })
.then(data => {
arr1 = data.splice(0);
console.log(arr1);
return arr1;
//arr1 = data.splice(0);
//exports.arr1 = arr1;
})}
module.exports = { poolData };
连同:
moduleL.poolData().then((result) => arr1 = result);
但是还是报错。只是一个不同的。我收到“Unhandled Rejection ConnectionError”,即使我单独运行 Logix 节点时它也运行得很好。
回答如下:更多推荐
我如何使用'await'或'.then'来处理带有Logix.js的node.js express中的异步导出?
发布评论