gpt4 book ai didi

javascript - socket io 内部的回调

转载 作者:行者123 更新时间:2023-11-30 12:22:20 25 4
gpt4 key购买 nike

当执行数据需要很长时间时,我遇到了套接字问题。例如:

socket.on('start', function(input){
var output = foo(input); //taking a very long time to get data, networking etc.
console.log("this is ending", output);
socket.emit('end',output);
});

似乎如果 foo(input) 执行需要很长时间,nodejs 实际上会在它仍然为 null 时首先发出输出。

如何确保在发出之前先完成执行?

我是这样修改的

    socket.on('several',function(meterIDArray){
console.log("I have receiever meterIDArray",meterIDArray);
meterIDs = meterIDArray.meterIDs;
foo(meterIDs,function(Datasets){
console.log("This is datasets",Datasets);
socket.emit('Datasets',Datasets);
});

});

然后我像这样修改了我的 foo

function foo(meterIDs,callback){
//this is what I meant by a long call.
var Datasets = [];
for (var i = meterIDs.length - 1; i >= 0; i--) {
datapoint.setMeterID(meterIDs[i],function(err, results){
datapoint.doRequest(null, function(err, results){
var dataAfter = [];
var step = 1;
for(var i = 0; i < results.timeseries.length; i = i + step) {
var item = results.timeseries[i];
for(date in item) {
dataAfter.push({x: date, y: item[date]})
}
}
console.log("This is data After",dataAfter);
Datasets.push(dataAfter);
});
});
}
callback(Datasets);
}

但还是一样的效果:socket 仍然发出 null。抱歉,如果这是一个幼稚的错误。谢谢!

最佳答案

如果你可以修改foo,你只需要这样:

socket.on('start', function(input){
foo(input, function (output) {
console.log("this is ending", output)
socket.emit('end', output)
))
})

您需要在服务器请求返回时触发回调。

更新:不能使用 for 循环 i 来跟踪已发出的请求数,必须在请求返回后跟踪。

function foo(meterIDs, callback) {
var Datasets = [];
var numberOfRequestsToMake = meterIDs.length;
for (var i = meterIDs.length - 1; i >= 0; i--) {
datapoint.setMeterID(meterIDs[i],function(err, results){
datapoint.doRequest(null, function(err, results){
var dataAfter = [];
var step = 1;
for(var i = 0; i < results.timeseries.length; i = i + step) {
var item = results.timeseries[i];
for(var date in item) {
dataAfter.push({x: date, y: item[date]})
}
}
console.log("This is data After",dataAfter);
Datasets.push(dataAfter);

numberOfRequestsToMake--;

// if this is the final return from the server
if (numberOfRequestsToMake === 0) {
callback(Datasets)
}
});
});
}
}

Promises are awesome though

关于javascript - socket io 内部的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30605903/

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