简体   繁体   中英

How to correctly use a callback function in NodeJS

Alright. Trying to make a very simple request here. First code with asynchronous Nodejs. According to everywhere I've checked, I'm doing this right. None of them explained really how callbacks work, they just say what to do, so I have no way of figuring it out intuitively.

const request = require("request");

function fetchData(url, json, callback) {
    request({
        url: url,
        json: json,
        method: "get"
    }, callback(error, response, body))
}

console.log(fetchData("https://www.yahoo.com", false, function(error, response, body) {
    if(!error && response.statusCode == 200) {
        return body;
    } else {
        return error;
    }
}));

Thanks

Two things- first, pass the callback variable into request() , don't call the function.

callback vs callback()

Second, you can't use the return value from the callback function. Call console.log() from inside the callback function.

Code with changes:

const request = require("request");

function fetchData(url, json, callback) {
    request({
        url: url,
        json: json,
        method: "get"
    }, callback)
}

fetchData("http://www.yahoo.com", false, function(error, response, body) {
    if(!error && response.statusCode == 200) {
        console.log(body);
    } else {
        console.log(error);
    }
}));

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