如何使节点http请求暂停执行直到完成

时间:2016-08-11 17:19:57

标签: node.js http sails.js

我从一个我希望传递给另一个函数的服务获得JSON响应。当我在var parsedData...行和return resp上放置断点时,解析数据行首先被击中。在继续编写代码之前,如何“等待”完成请求?

var data = sendRequest(options);
var parsedData = parseData(commits);

var sendRequest = function (options) {
    var resp = {}
    var request = https.request(options, function (response) {
        var body = '';
        response.on("data", function (chunk) {
            body += chunk.toString('utf8');
        });

        response.on("error", function(e){
            console.log(e);
        })

        response.on("end", function () {
            resp = JSON.parse(body);
            return resp;
        });
    });
    request.end();
}

1 个答案:

答案 0 :(得分:0)

sendRequest

添加回调参数
var data = sendRequest(options, function(){
    var parsedData = parseData(commits);
});

var sendRequest = function (options, callback) {
    var resp = {}
    var request = https.request(options, function (response) {
        var body = '';
        response.on("data", function (chunk) {
            body += chunk.toString('utf8');
        });

        response.on("error", function(e){
            console.log(e);
        })

        response.on("end", function () {
            resp = JSON.parse(body);
            callback(resp);
        });
    });
    request.end();
}