gpt4 book ai didi

javascript - 如何在Node.js中定义对象

转载 作者:行者123 更新时间:2023-11-28 03:03:14 25 4
gpt4 key购买 nike

我正在尝试为对象分配一个值,但是当我尝试显示它时,它总是返回[]。这是我的一段代码

const exspress = require("express");
const aplication = exspress();
//body parser for informaton monggo
const bodyparser = require("body-parser");
//configuration for node aplication
aplication.use(
bodyparser.urlencoded({
extended: false
})
);
const mongose = require("mongoose");

const router = exspress.Router();

const PingModel = mongose.model("Ping");

const ping = require("ping");
var tcpp = require("tcp-ping");
var obj = Array();
var a = 0;
var b = pingtime;
for(a; a<b; a++){
ping.promise.probe(host).then(function(data) {
const storePing = new PingModel();
storePing.hostPing = host;
storePing.hostIp = data.numeric_host;
if (data.alive) {
storePing.hostStatus = "Ok";
} else {
storePing.hostStatus = "Not_ok";
}
if (data.alive) {
storePing.hostLatency = "true";
} else {
storePing.hostLatency = "false";
}
storePing.save();
window.obj = storePing
// return this.obj[a] = storePing;
});
console.log(obj);
}
module.exports = router;

你们能告诉我如何定义一个对象并用我在单独的代码/函数中使用它的数据/值填充它吗?

最佳答案

尝试更改window.objobj作为您的obj只是一个变量,它不在 window 上对象

此外,在声明对象时,您已将其声明为数组。如果你想要一个对象,你可以使用 var obj = {}; ,尽管如此,我们还是用 storePing 重新分配它

此外,您还需要移动您的 console.log进入then promise 的回调,因为它是您拥有的异步代码 - 目前,您的 console.log将在 then 之前触发 promise 的回调已执行,因此 obj还没有达到您期望的值

一些很长的东西 -

const router = exspress.Router();

const PingModel = mongose.model("Ping");

const ping = require("ping");
var tcpp = require("tcp-ping");
var obj = {}; // NOTE, object instead of array, though this gets reassigned anyway, so doesn't really matter
var a = 0;
var b = pingtime;
for(a; a<b; a++){
ping.promise.probe(host).then(function(data) {
const storePing = new PingModel();
storePing.hostPing = host;
storePing.hostIp = data.numeric_host;
if (data.alive) {
storePing.hostStatus = "Ok";
} else {
storePing.hostStatus = "Not_ok";
}
if (data.alive) {
storePing.hostLatency = "true";
} else {
storePing.hostLatency = "false";
}
storePing.save();
obj = storePing // <-- NOTE, no window object

console.log(obj); // <-- NOTE, logging inside the then callback
// return this.obj[a] = storePing;
});
}
module.exports = router;

关于javascript - 如何在Node.js中定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60809661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com