I have the following script in node.js:
var db = require("redis");
var dbclient = db.createClient();
function doSomeUpload()
dbclient.zrangs("noper", 0, 5000, function (err, replies){
var lengthNum = replies.length;
for (var i=0; i < replies.length; i++){
// Upload the file with s3 client
uploader.on('end', function();
lengthNum--;
if (lengthNum == 0){
console.log("Done!")
return;
}
})
})
doSomeUpload()
When I run this script: node scriptupload.js
, Done!
is printed, but the script never ending. It is still run, and I have to do ctrl+c
in order to end the node.js process.
Why is it never ending (even when the function returns..)
答案 0 :(得分:0)
Your loop is very awkward, you should decrease a counter instead, and first initialize it with the replies.length
. Otherwise it's easy to get an infinite loop.
Also there is an error on the last line of the for loop, where you pass an empty callback to the uploader's end
event.
You also missed a couple of semicolons (which are optional, but make the program clear).
var db = require("redis");
var dbclient = db.createClient();
function doSomeUpload() {
dbclient.zrangs("noper", 0, 5000, function (err, replies) {
for (var i = replies.length; i > 0; i--) {
// Upload the file with s3 client
uploader.on('end', function() {});
}
});
});
doSomeUpload();
答案 1 :(得分:0)
我会在你的脚本末尾放一个console.log("Returned");
。它应该被调用,但也许其中一个S3上传正在挂起。
除此之外,您还有语法错误:
存在语义错误或不必要的代码:
以下是经过纠正的代码,其中包含一些简化,命名增强和错误处理:
var db = require("redis");
var dbclient = db.createClient();
function doSomeUpload(){
dbclient.zrangs("noper", 0, 5000, function(err, replies){
if (err){
console.error(err);
} else {
var uploadsRemaining = replies.length;
replies.forEach(function(reply){
// Upload the file with s3 client
uploader.on('end', function() {
uploadsRemaining--;
if (uploadsRemaining == 0){
console.log("Done!");
}
});
});
}
});
}
doSomeUpload();
我认为该错误存在于未共享的代码中。 S3上传可能会被阻止,这可以通过设置一个10秒的低超时来轻松验证。
非常值得使用JSLint或构建它的编辑器或类似的东西(Emacs和WebStorm都这样做): http://jslint.com/
运行代码,直到它清理干净。在提交到在线工具之前,请务必清除代码(删除凭据或IP敏感代码)。下载该工具并在本地运行它或使用带有JavaScript代码检查的编辑器可能更好。
在生产中,您的代码应该没有错误或警告。这样做显着限制了混淆运行时行为的空间。
答案 2 :(得分:-1)
you need to decrease your counter instead of increasing, otherwise it will never be smaller then replies.length:
for (var i=replies.length; i > 0; i--){
// Upload the file with s3 client
uploader.on('end', function();
// lengthNum--; // You don't need this anymore
if (i == 0){
console.log("Done!")
return;
}
})
greetings