Pergunta

I am currently trying to make a node.js wrapper for a MediaWiki extension and I need to be able to log in. Everything so far seems to be working but I cannot get the script to halt and wait for the request to finish before returning. This is crucial because the request must finish before it returns in order for it to return the proper value and not undefined. I am using the request module for node.js. The current HTTP POST handler is as follows

var post = function(data) {

    var r;
    var options = {};
        options.url = module.exports.apipath;
        options.method = "POST";
        options.form = data;

    request(options, function(error, response, body) {

         if (!error) {

            if(response.statusCode == 200) {

                try {

                    if((typeof body) == "string") {

                        var result = JSON.parse(body);

                        r = result;
                    } else {

                        r = body;
                    }
                } catch (e) {

                    return;
                }
            }
        } else {

            console.log("Error: " + error);
        }
    });

    return r;
};
Foi útil?

Solução

Because the request method is asynchronous, you need to make your wrapper function asynchronous as well:

var post = function(data, callback) {

    var r;
    var options = {};
        options.url = module.exports.apipath;
        options.method = "POST";
        options.form = data;

    request(options, function(error, response, body) {

         if (!error) {

            if(response.statusCode == 200) {

                try {

                    if((typeof body) == "string") {

                        var result = JSON.parse(body);

                        r = result;
                    } else {

                        r = body;
                    }

                    // Call callback with no error, and result of request
                    return callback(null, r);

                } catch (e) {

                    // Call callback with error
                    return callback(e);
                }
            }
        } else {

            console.log("Error: " + error);
            return callback(error);
        }
    });

}

Then you would call post with a callback function as the second argument, to be run when the request was complete. By convention, your callback should take at least two arguments: an error, which should be null if everything works out okay, and a result which is the result of the asynchronous process:

post ({foo: 'bar'}, function(err, result) {...});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top