javascript - 无法返回node.js中的变量

标签 javascript node.js

我从函数中返回变量 uploadFile,当我尝试在另一个变量中访问它时,它给了我未定义

function upload(req, res, callback) {
    var dir = 'uploads/';

    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
    }

    console.log(req.files.file1);
    console.log(req.files.file2);

    var uploadFiles = {
        ext1: path.extname(req.files.file1.originalname),
        path1: req.files.file1.path,
        ext2: path.extname(req.files.file2.originalname),
        path2: req.files.file2.path
    }
    return callback(uploadFiles);
}

这是我调用上传函数的函数,我想我做错了,我得到Callback is not a function作为错误...请指导我

function sendMail(req, res) {
    var data = req.body;
     upload(req,res);
// checking the condition if the file has been uploaded
    if (uploadFiles) {
        data_to_send.attachments = [{
            filename: 'file1' + uploadFiles.file1ext,
            filePath: uploadFiles.file1Path 
        }, {
            filename: 'file2' + uploadFiles.file2ext,
            filePath: uploadFiles.file2Path
        }]
    }
    console.log(data_to_send.attachments)
    smtpTransport.sendMail({
            from: data_to_send.from,
            to: data_to_send.to,
            subject: data_to_send.subject,
            atachments: data_to_send.attachments,
            text: data_to_send.text,
            html: data_to_send.html
        },
//.........

最佳答案

问题是,在您的上传函数中,您没有检查回调是否实际传递(并且不是未定义)。另外,您没有返回您的值,您实际上正在返回任何回调正在返回的内容。

下面是一些可能对您有帮助的代码:

// inside your upload function
var uploadFiles = {
        ext1: path.extname(req.files.file1.originalname),
        path1: req.files.file1.path,
        ext2: path.extname(req.files.file2.originalname),
        path2: req.files.file2.path
    }
if (callback) {
    callback(uploadFiles);
}

//inside your sendMail (notice the 3rd parameter passed to upload)
upload(req, res, function (uploadFiles) {
    if (uploadFiles) {
        data_to_send.attachments = [{
            filename: 'file1' + uploadFiles.file1ext,
            filePath: uploadFiles.file1Path 
        }, {
            filename: 'file2' + uploadFiles.file2ext,
            filePath: uploadFiles.file2Path
        }]
    }
    // rest of the code goes here, inside the callback.
});

现在您将真正按照您的意愿在回调中收到文件。

关于javascript - 无法返回node.js中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36808391/

相关文章:

javascript - 如何让 ASP.net 在 JavaScript jQuery.Load 调用中填写本地服务器

javascript - jQuery 匿名函数 - 嵌套函数

javascript - 将坐标转换为等距坐标,反之亦然不起作用

javascript - 如何将加密形式的密码从 ReactJS 发送到 ExpressJS?

node.js - 为接口(interface)编写 Apollo 解析器

javascript - 商店软件更新验证码不可见

javascript - 如何跨多个代码镜像实例进行搜索?

node.js - 通过 node.js 应用程序在 redis 中保存嵌套哈希

node.js - 如何在另一个文件夹中使用我的主应用程序文件夹中的 Mongoose 模型?

node.js - 使用 KeystoneJs 的 Mongoose 二级人口