使模块异步 - nodejs

时间:2015-04-22 09:53:49

标签: node.js asynchronous

我有以下函数,我将其导出以使用async.series方法在其他地方使用。但是,当我在IDE的调试器中运行apiCaller._get时,它会在执行get请求之前返回undefined。尽管如此,仍然执行get请求。但是`apiCaller._get不是异步的,我知道它需要进行回调,但是我不知道在哪里调用回调。

var http = require("http");
var querystring = require("querystring");
var _ = require("underscore");

apiCaller = {};

apiCaller.token = null;

var server=http.createServer(function(req,res){});

server.listen(8080);

apiCaller._get = function (context, config, TheCallback) {

    // get the parameters for our querytring
    var oauthParams = _.pick(config, "client_id", "client_secret", "grant_type");

    // create the querystring
    var params = querystring.stringify(oauthParams);

    var options = {
        method: "GET",
        hostname: config.host,
        path: "/my/path/to/token?" + params,
        headers : {
            'Content-Type': "application/json",
            'Accept': "application/json"
        }
    };

    var _callback = function(response) {
        console.log('STATUS: ' + response.statusCode);
        console.log('HEADERS: ' + JSON.stringify(response.headers));
        var str = '';

        //another chunk of data has been recieved, so append it to `str`
        response.on('data', function (chunk) {
            str += chunk;
        });

        // error response
        response.on("error", function (error) {
            if ( !context ) {
                console.error("Something went wrong with the api response.");
                return;
            }
            context.done(new Error("Something went wrong with the api response."));
        });

        //the whole response has been recieved, so we just print it out here
        response.on('end', function () {

            apiCaller.token = JSON.parse(str).access_token;
            // we want to stop the request if token is not correct
            if ( !apiCaller.token || apiCaller.token === undefined || apiCaller.token === null ) {
                if ( !context ) {
                    console.error("Something went wrong with the token. Wrong token! Token: %s", apiCaller.token);
                    return;
                }
                console.error("Token: %s", apiCaller.token);
                context.done(new Error("Something went wrong with the token. Wrong token!"));
            }
            console.log(str);
            console.log(apiCaller.token);

        });
    };

    var request = http.request(options, _callback);

    request.on('error', function(e) {
        console.log('problem with request');
    });

    request.end();
};

1 个答案:

答案 0 :(得分:2)

将函数作为形式参数TheCallback传入,并在end函数中response的{​​{1}}事件处理程序中调用它。

E.g。

_callback

<强>更新

通过使用var _callback = function(response) { console.log('STATUS: ' + response.statusCode); console.log('HEADERS: ' + JSON.stringify(response.headers)); var str = ''; //another chunk of data has been recieved, so append it to `str` response.on('data', function (chunk) { str += chunk; }); // error response response.on("error", function (error) { if ( !context ) { console.error("Something went wrong with the api response."); return; } context.done(new Error("Something went wrong with the api response.")); }); //the whole response has been recieved, so we just print it out here response.on('end', function () { apiCaller.token = JSON.parse(str).access_token; // we want to stop the request if token is not correct if ( !apiCaller.token || apiCaller.token === undefined || apiCaller.token === null ) { if ( !context ) { console.error("Something went wrong with the token. Wrong token! Token: %s", apiCaller.token); return; } console.error("Token: %s", apiCaller.token); context.done(new Error("Something went wrong with the token. Wrong token!")); } console.log(str); console.log(apiCaller.token); TheCallback.apply(context, arguments); }); callapply,您可以在您选择的上下文中执行回调函数。它可能是bind提供的对象或您需要的任何其他内容。如果您不需要为回调执行更改此绑定,请使用context简单地调用它。