简体   繁体   中英

how to write custom callback function in js

i want to set message to my callback after get callback of reading file like this:

exp.getServerHandler=function (request,response){

    if(request.url.startsWith("/static/")){
        //passing my custom callback function as an input param
        fileReadHandler(request,response,function callback(message){
            console.log(message);
        });
    }
};

function fileReadHandler(request,response,callback){
    fs.readFile(request.url.substr(1),
        function(err,data) {
            if(err){
                response.end("bad request");
                response.statusCode=400;
                //here i want to set message as my callback param
                callback("failed");
            }else{
                response.end(data);
                //here i want to set message as my callback param
                callback("successful");
            }
        }
    );
}

but console didn't log the message of my callback! where is the problem? is this the correct way of doing this?

edit:

this code is works fine and correct

use this code:

exp.getServerHandler=function (request,response){
    if(request.url.startsWith("/static/")){
       //passing my custom callback function as an input param
       fileReadHandler(request,response,function callback(message){               
           if (window.console && window.console.log)
               window.console.log(message);
       });
    }
};
  1. Check console object, because eq. IE console object supply only if console window opened
  2. Use complete path window.console .

Try removing the callback function name when passing it to fileReadHandler like this:

exp.getServerHandler=function (request,response){

    if(request.url.startsWith("/static/")){
        //passing my custom callback function as an input param
        fileReadHandler(request,response,function(message){
            console.log(message);
        });
    }
};

function fileReadHandler(request,response,callback){
    fs.readFile(request.url.substr(1),
        function(err,data) {
            if(err){
                response.end("bad request");
                response.statusCode=400;
                //here i want to set message as my callback param
                callback("failed");
            }else{
                response.end(data);
                //here i want to set message as my callback param
                callback("successful");
            }
        }
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM