我有这个代码
function imagenesIn(errU,errores)
{
if(errU) throw errU;
var directorios=new Array();
var origenDir='';
var destinoDir='';
if(errores=='')
{
if(campos.img instanceof Array)
{
for(file in campos.img)
{
origenDir='';
destinoDir='';
origenDir=campos.img[file].path;
destinoDir='/uploads/publish/alquiler/'+req.session.passport.user+campos.img[file].name;
fs.rename(origenDir,process.cwd()+'/public'+destinoDir,function(err)
{
if (err) throw err;
directorios.push(destinoDir);
console.dir(directorios)
})
}
}
}else{
res.send(errores)
}
return directorios;
},
我想在directorios中获取req.files.img中所有文件内容的命运的数组 位于campos.img
但是当我在控制台中打印时发生了这种情况
"img": [
"/uploads/publish/alquiler/andres@hotmail.comTulips.jpg",
"/uploads/publish/alquiler/andres@hotmail.comTulips.jpg"
],
我正在尝试得到这个结果
"img": [
"/uploads/publish/alquiler/andres@hotmail.comTulips.jpg", //first img
"/uploads/publish/alquiler/andres@hotmail.flowers.jpg"//second img
],
为什么 .push() 方法只放置第一个图像目录而不放置第二个??? 我错过了什么???
tnx
最佳答案
你的问题在于
fs.rename(origenDir,process.cwd()+'/public'+destinoDir,function(err)
{
if (err) throw err;
directorios.push(destinoDir);
console.dir(directorios)
})
当您执行操作时,您的 push()
尚未真正运行
return directorios;
您需要确保最后完成对fs.rename(...)
的调用(这不是,我重复不是,必然与最后开始相同的调用)处理所有调用都已完成的情况。使用异步调用,您不能在启动一堆调用并执行返回
后就失败了;您必须将所有工作完成后要运行的代码放在回调中,该回调解决了我之前所说的“句柄”。
像 async.js 这样的控制流库可以简化您的代码,但您需要了解这样一个概念:一旦您的函数变为异步,它后面的所有内容也必须是异步的。
关于javascript - 为什么 array.push 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12491126/