gpt4 book ai didi

node.js - 如何在 Nodejs 循环中将值收集到数组中?

转载 作者:太空宇宙 更新时间:2023-11-04 02:30:34 25 4
gpt4 key购买 nike

我编写了下面的代码,尝试将视频收集到数组中然后返回。代码是错误的,但我无法找出正确的方法来做到这一点。

var redis = require('redis');
var client = redis.createClient();

app.get('/topvideos', function(req, res){
res.type('application/json');
var topvideos = [];

client.hkeys("topvideos", function(err,replies) {
console.log("Results for video:");
console.log(replies.length + " videos:");

replies.forEach(function (reply, i) {

client.hget("topvideos",i, function (err, reply) {
console.log(i + ": " + reply );
topvideos.push(reply);
});
});

}
var string = JSON.stringify(topvideos)
res.send(string);
});

有我可以遵循的优雅模式吗?

最佳答案

大概是.hkeys方法是异步的。这意味着您必须编写知道所有异步项目何时完成的代码,以便您可以(并且只有那时)到达最终的 res.send()随着结果的积累。

有很多方法可以跟踪所有异步操作何时完成。我最喜欢的是 promise 所有涉及的功能并使用 Promise.all() 。但是,由于您尚未在此代码中使用 Promise,因此这里有一个使用手动计数器的方法。每当启动异步任务时就增加计数器。每当完成异步任务时就递减计数器。当计数器为零时,所有异步操作都完成:

var redis = require('redis');
var client = redis.createClient();

app.get('/topvideos', function(req, res){
res.type('application/json');
var topvideos = [];
var cntRemaining = 0;

client.hkeys("topvideos", function(err,replies) {
console.log("Results for video:");
console.log(replies.length + " videos:");

replies.forEach(function (reply, i) {
++cntRemaining;

client.hget("topvideos",i, function (err, reply) {
console.log(i + ": " + reply );
topvideos.push(reply);
--cntRemaining;
if (cntRemaining === 0) {
res.send(JSON.stringify(topvideos));
}
});
});

}
});

关于node.js - 如何在 Nodejs 循环中将值收集到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27119280/

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