我如何使用'await'或'.then'来处理带有Logix.js的node.js express中的异步导出?

编程入门 行业动态 更新时间:2024-10-04 09:24:57

我<a href=https://www.elefans.com/category/jswz/34/1771452.html style=如何使用'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中的异步导出?

本文发布于:2024-05-31 05:49:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771339.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   await   Logix   node   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!