[英]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.