【发布时间】:2026-02-17 23:05:01
【问题描述】:
我正在尝试使用 node.js 的异步模块并行上传多个文件。我的代码如下所示:
// fileArr is an array of objects. each object contains the attributes of the file to be uploaded - filename, path, destination path, etc.
// toUpload is an array to which i push all the functions i want to execute with async.parallel
for (i=0; i<fileArr.length; i++) {
var src = fileArr[i]['path']
var dest = fileArr[i]['dest']
var fn = function(cb) { self.upload(src, dest, headers, function(err, url) {
cb(null, url)
})
}
toUpload.push(fn)
} // for loop ends here
async.parallel(toUpload, function(err, results) {
console.log('results: ' + results)
})
我的问题:对于 n = toUpload 中的函数数,结果数组回调包含数组中最后一个并行任务的结果,n 次。我想不通。似乎每个函数都应该使用 (null, url) 将自己的回调返回给并行函数。
还有 - 当我尝试使用 src 和 dest 的定义直接调用 self.upload 函数时:
self.upload(fileArr[i]['path'], fileArr[i]['dest'], headers, function(err, url) {
cb(null, url)
})
我收到一条错误消息,提示“无法读取未定义的属性‘路径’”。所以,fileArr[i] 是未定义的。为什么会这样?我觉得任务和范围的进行有些奇怪......
如果问题(和代码)不是很明显,我对编程还是很陌生..
【问题讨论】:
标签: node.js asynchronous