javascript - 为什么 array.push 不起作用?

标签 javascript node.js express

我有这个代码

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/

相关文章:

node.js - 在 Node Express 中包含自定义模块

node.js - 无法使用 ExpressJS 与 oauth2orize 提供程序保持持久登录

node.js - MEAN.io 中的页面标题重复

node.js - 管道流到 graphicsmagick/imagemagick 子进程

javascript - 避免传递请求对象

node.js - Node 强大,创建不必要的零字节大小的文件

javascript - 根据首字母匹配搜索或过滤数据

Javascript 相当于 Python 的 locals()?

javascript - 获取图片alt,添加为父类

javascript - 带 RequireJS 的 Underscore.string