NodeJS函数返回一个未定义的函数。

时间:2018-04-26 14:25:56

标签: javascript node.js

我正在尝试构建一个附加到文件的泛型函数。根据结果​​,函数将返回200或500的状态。

初始设置应调用该函数并返回其中一个状态。调用该方法后,我收到一个空对象。

该函数是类的一部分,并且已添加所有必需的导入。 我确实尝试返回fs.appendFile但我设法收到相同的结果。

/**
 * A functio which writes a data into a file
 * @param  {[string]} fileName A file location with file name string
 * @param  {[string]} msg      A data to be saved
 * @return {[object]}          A response object with response code and msg.
 */
static toFile(fileName, msg) {
    fs.appendFile(fileName, msg, function(err) {
        let responseObject = {};
        if (err) {
            responseObject.status = 500;
            responseObject.msg = 'Error occured please view ' + fileName;
            return responseObject;
        }
        responseObject.status = 200;
        responseObject.msg = 'Success, file has been created ' + fileName;

        return responseObject;
    });
}

2 个答案:

答案 0 :(得分:1)

那是因为你回到了回调中。尝试使用Promise或添加回调参数。

承诺

/**
 * A functio which writes a data into a file
 * @param  {[string]} fileName A file location with file name string
 * @param  {[string]} msg      A data to be saved
 * @return {[object]}          A response object with response code and msg.
 */
static toFile(fileName, msg) {
    return new Promise(resolve => {
        fs.appendFile(fileName, msg, function(err) {
            let responseObject = {};
            if (err) {
                responseObject.status = 500;
                responseObject.msg = 'Error occured please view ' + fileName;
            } else {
                responseObject.status = 200;
                responseObject.msg = 'Success, file has been created ' + fileName;
            }
            resolve(responseObject);
        });
    });
}

toFile('myfile.txt', 'Hello world!')
    .then(data => {
        console.log(data); // will print responseObject
    });

使用回调函数

/**
 * A functio which writes a data into a file
 * @param  {[string]} fileName A file location with file name string
 * @param  {[string]} msg      A data to be saved
 * @return {[object]}          A response object with response code and msg.
 */
static toFile(fileName, msg, cb) {
    fs.appendFile(fileName, msg, function(err) {
        let responseObject = {};
        if (err) {
            responseObject.status = 500;
            responseObject.msg = 'Error occured please view ' + fileName;
        } else {
            responseObject.status = 200;
            responseObject.msg = 'Success, file has been created ' + fileName;
        }
        cb(responseObject);
    });
}

toFile('myfile.txt', 'Hello world!', function(response) {
    console.log(response); // will print your responseObject
});

答案 1 :(得分:1)

这里的问题是fs.appendFile函数的工作方式。 该函数是异步的...所以基本上你可以看到你的函数如下:

static toFile(fileName, msg) {
    fs.appendFile(fileName, msg, function(err) {
        let responseObject = {};
        if (err) {
            responseObject.status = 500;
            responseObject.msg = 'Error occured please view ' + fileName;
            return responseObject;
        }
        responseObject.status = 200;
        responseObject.msg = 'Success, file has been created ' + fileName;

        return responseObject; //this wont be assigned to anything.
    });
    return undefined; //this is why you get undefined 
}

你可以使用2种方法:

Callback approach: 当你得到响应对象时,这将触发你的cb函数。

static toFile(fileName, msg, cb) { //cb is a function
    fs.appendFile(fileName, msg, function(err) {
        let responseObject = {};
        if (err) {
            responseObject.status = 500;
            responseObject.msg = 'Error occured please view ' + fileName;
            return responseObject;
        }
        responseObject.status = 200;
        responseObject.msg = 'Success, file has been created ' + fileName;

        cb(responseObject); //instead of returning, call your cb function and use it as you please.
    });
}

Promise approach

这会在结算时返回响应对象,当然你必须在toFile函数之外处理一个promise。

   static toFile(fileName, msg) { //cb is a function
    return new Promise((resolve, reject) => {
            fs.appendFile(fileName, msg, function(err) {
                let responseObject = {};
                if (err) {
                    responseObject.status = 500;
                    responseObject.msg = 'Error occured please view ' + fileName;
                    reject(responseObject)
                }
                responseObject.status = 200;
                responseObject.msg = 'Success, file has been created ' + fileName;

                resolve(responseObject)
            });
        }
    }