i have this code
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;
},
i want to get in directorios an array of the destiny of all files content in req.files.img
that are in campos.img
but when i print in console this happend
"img": [
"/uploads/publish/alquiler/andres@hotmail.comTulips.jpg",
"/uploads/publish/alquiler/andres@hotmail.comTulips.jpg"
],
im trying to get this result
"img": [
"/uploads/publish/alquiler/andres@hotmail.comTulips.jpg", //first img
"/uploads/publish/alquiler/andres@hotmail.flowers.jpg"//second img
],
why .push() method put only the first image directory and not the second???
i miss something???
tnx
Your problem is that in
your
push()won’t have actually run by the time you doYou need to make sure that the call to
fs.rename(...)that finishes last (which is not, I repeat not, necessarily going to be the same call that starts last) handles the case where all the calls have finished. Using asynchronous calls, you cannot just fall through after firing up a bunch of them and do areturn; you will have to put the code that you want to run after all the work is done in a callback that addresses what I called “handles” earlier.Control-flow libraries like async.js could simplify your code, but you’ll need to get your head around the notion that once your function goes async everything that follows it has to be async as well.