gpt4 book ai didi

javascript - 我如何更新来自差异 socket.io 事件的消息?

转载 作者:搜寻专家 更新时间:2023-11-01 04:53:22 24 4
gpt4 key购买 nike

我正在使用具有差异事件 channelName1channelName2 的 api>

//...this the realtime record
socket.on(channelName1, message => {
console.log(channelName1, message1);
//this return single item list in realtime`[{"price":100,"size":0.001}]`
});

//realtime snapshot collection of records
socket.on(channelName2, message => {
console.log(channelName2, message2);
//this return the collection `[{"price":100,"size":0.01}, {"price":200,"size":0.02} ]`
$('#live').text(message2)
});

如果我发现 price":100 出现在集合 message2 中,我想更新 message2 的大小,所以更新后 message2 将

[{"price":100,"size":0.001}, {"price":200,"size":0.002} ]

谁能指导我如何进行从 channelName1 到 ChannelName2 数据的更新?

最佳答案

您必须将单件元素存放在某个地方,当收集品到达时您需要:

  1. 使用 map 处理集合中的每一项.
  2. 对于每个项目,尝试 find它在存储的单个项目中。
  3. 如果找到,请更改大小。

我还在集合中包含了一条无法找到的记录,因此您可以看到那里发生了什么:它保持不变。

忽略我为模拟套接字所做的小改动。希望您能看到我正在做的事情的大局。

希望这对您有所帮助,祝您编码愉快。

// Stores each single item that arrives.
let singleItems = [];

// ...this is the realtime record.
function socketOn1(channelName1, message1) {
console.log(channelName1, message1);

// Store each single item as it arrives.
singleItems.push(message1[0]);
};

// realtime snapshot collection of records
function socketOn2(channelName2, message2) {
console.log(channelName2, message2);

// For each element in the collection, find
// the same record in the single items and
// if found, update the price.
results = message2.map((elem) => {
found = singleItems.find(
(single) => single.price === elem.price
)
if (found) {
elem.size = found.size
}
return elem
})

console.log('results:')
console.log(results)
};


// This stuff just simulates stuff arriving to sockets.
// You can ignore it if you want. But look at the order
// in which they are called.

let singleItemsMock = [{
"price": 100,
"size": 0.01
},
{
"price": 50,
"size": 0.02
},
{
"price": 25,
"size": 0.03
},
{
"price": 10,
"size": 0.04
}
]

let collectionMock = [{
"price": 100,
"size": 0.001
},
{
"price": 50,
"size": 0.002
},
{
"price": 13,
"size": 0.005
}
]

socketOn1(null, [singleItemsMock[0]])
socketOn1(null, [singleItemsMock[1]])
socketOn1(null, [singleItemsMock[2]])
socketOn1(null, [singleItemsMock[3]])

socketOn2(null, collectionMock)

关于javascript - 我如何更新来自差异 socket.io 事件的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58072039/

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