gpt4 book ai didi

javascript - 观察 NodeJS 集群是否退出

转载 作者:行者123 更新时间:2023-12-03 10:57:22 29 4
gpt4 key购买 nike

我很难理解让 Node.js 进程(异步)运行但仍然触发“退出”状态,以便在 CPU 处理完成后我可以做更多事情。

例如,我有一个 Google 地方信息抓取工具,可以在所有可用的 CPU 上高效地分发 http 请求。

} else if (cluster.isWorker) {
// Code to run if we're in a worker process

// Send the object we created above from variables so they're available to the workers
process.on('message', function(clusterDivisionObject) {
var tempArray;

// Send the chunk of array appropriate for this cluster to process, then request it's place details
tempArray = clusterDivisionObject.placeIdArray.splice(((cluster.worker.id * clusterDivisionObject.clusterDivision) - clusterDivisionObject.clusterDivision), clusterDivisionObject.clusterDivision);
tempArray.forEach(function(arrayItem, index, array){
request({url: config.detailsRequestURI + '?key=' + config.apiKey + '&placeid=' + arrayItem, headers: config.headers}, detailsRequest);
});
});
}

这里真正的问题是我发送异步 request() 语句的最后一行。代码执行正确,但一旦我点击回调 (detailsRequest) 执行某些操作(在本例中,写入 json 文件),我就无法控制退出进程。我的回调函数:

function detailsRequest(error, response, body) {
if (!error && response.statusCode == 200) {
var detailsBody = JSON.parse(body);
...
}
}

...不知道哪个进程正在运行它或它已经进行了多少次迭代(在整个 tempArray 耗尽后触发退出)。因此,假设一个集群正在为 x 长度的 tempArray 运行 request(),那么当该情况时如何触发 process.exit(0) tempArray.forEach(){} 已完成?

我尝试在 tempArray.forEach(){} 之后直接调用 process.exit(0),但在 request() 运行之前该进程就会终止。 是否有任何有效的方法可以更好地观察进程来调用它的退出,或者我真的在尝试解决一个不可能存在的问题,因为 request() 是异步的并且可以被调用或没有按任何顺序调用?

最佳答案

您需要异步流控制。在所有请求完成之前,您不希望进程退出。相反,您要求 Node 发出所有这些请求,然后退出该进程。结账async.js或其他一些流量控制库。但你需要这样的东西:

var tempArray;
var counter = 0;

tempArray = []; // same as above

// Without asyncjs
tempArray.forEach(function(arrayItem, index, array){
request({url: config.detailsRequestURI + '?key=' + config.apiKey +'&placeid=' + arrayItem, headers: config.headers}, detailsRequest);
});

function detailsRequest(){
// increment counter and handle response
// this callback gets called N times.
counter +=1;
if(counter >= tempArray.length){ process.exit(0); }
}


//With async.js:

async.map(tempArray, sendRequestFunc, function finalDone(err, results){
// here you can check results array which has response
// and then exit
process.exit(0);
});

function sendRequestFunc(el, done){
// done callback as per async docs
// done must be invoked here or the final callback is never triggered
request({url:'same as above'}, done)
}

请记住,您可能需要添加额外的错误或不良响应检查并进行相应的处理。

仅当请求返回响应或错误(异步)时才会调用 sendRequestFunc 中的完成回调,并且仅当所有响应都返回时才会调用最后一个异步回调“finalDone”。

关于javascript - 观察 NodeJS 集群是否退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28219550/

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