简体   繁体   中英

Proper way to use a callback in node.js

I know that I need to use a callback here, but all attempts have failed so far. I would like the console.log to log true or false. Thank you in advance.

var req_fn = function () {
        request(url, function(error, response, html){
        if(!error){            
            parseString(response.body ,function (err, result){
                var raw_json = result;
                var current_zip = get_current_zip(raw_json);

                if (current_zip.toString() === pack.creator_zip.toString() ) {   
                    return true; // would like to return this value
                } else {            
                    return false; // or this one
                }
            });
        }
    });
};

console.log(req_fn());

Here's what a callback would look like in that function

var req_fn = function (callback) {
    request(url, function (error, response, html) {
        if (err) {
            callback(err, null);
        }else {
            parseString(response.body, function (err, result) {
                if (err) {
                    callback(err, null);
                } else {
                    var raw_json = result;
                    var current_zip = get_current_zip(raw_json);
                    var result = current_zip.toString() === pack.creator_zip.toString();

                    callback(null, result);
                }
            });
        }
    });
};

req_fn(function(err, result))
    if (!err) console.log(result);
});

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