[英]How do I destructure this Object?
const WebSocket = require('ws')
let socket = new WebSocket('wss://ftx.com/ws/');
const dataObject = {'op': 'subscribe', 'channel': 'trades', 'market': 'BTC-PERP'};
socket.onopen = function() {
// Send an initial message
socket.send(JSON.stringify(dataObject));
console.log('Connected')
messages = []
socket.onmessage = (msg) => {
const priceData = JSON.parse(msg.data)
messages.push(priceData.data)
console.log(priceData.data)
}
// Listen for socket closes
socket.onclose = function(event) {
console.log('Client notified socket has closed', event);
};
// To close the socket....
// socket.close()
};
[nodemon] starting `node socket-ftx.js`
Connected
undefined
[
{
id: 5014962233,
price: 19280,
size: 0.03,
side: 'sell',
liquidation: false,
time: '2022-09-22T20:24:52.011309+00:00'
},
{
id: 5014962234,
price: 19280,
size: 0.02,
side: 'sell',
liquidation: false,
time: '2022-09-22T20:24:52.011309+00:00'
},
{
id: 5014962235,
price: 19280,
size: 0.0047,
side: 'sell',
liquidation: false,
time: '2022-09-22T20:24:52.011309+00:00'
}
]
我正在尝试将价格和大小元素存储到一个数组中,但是我无法从响应中解析该数组。
priceData.data[0].price 不起作用。 它会导致 TypeError。 我已经测试过(typeof 通过 priceData.data),它记录为 object 而不是数组。 我在这里很困惑...
编辑**
console.log('Connected')
socket.onmessage = (msg) => {
const priceData = JSON.parse(msg.data)
priceArray = []
if (Array.isArray(priceData.data) /* you might add an additional check if the msg contains an identifier of the data type */) {
const price = priceData.data[0].price
if (price > 0) {
priceArray.push(price)
console.log(priceArray[0])
}
}
}
这行得通! 谢谢您的帮助!
问题可能是 websocket 有时会向您发送不是 priceData arrays 的消息。 您需要在将其作为数组操作之前添加一个检查。
socket.onopen = function() {
// Send an initial message
socket.send(JSON.stringify(dataObject));
console.log('Connected')
messages = []
socket.onmessage = (msg) => {
// You could start by adding a log on the message, it might help you debug the issue
// [EDITED OUT as msg is an Event and JSON.stringify will just return an empty object] console.log(`Message value: ${JSON.stringify(msg)}`);
console.log(`Message value: ${msg.data}`);
const priceData = JSON.parse(msg.data)
if (Array.isArray(priceData.data) /* you might add an additional check if the msg contains an identifier of the data type */) {
// Do your array manipulations here
} else {
// it's not a priceData array, do something else if needed
}
}
// Listen for socket closes
socket.onclose = function(event) {
console.log('Client notified socket has closed', event);
};
// To close the socket....
// socket.close()
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.