节点js在20秒后发送多个请求

时间:2017-07-24 06:37:24

标签: javascript node.js

如果响应时间为20秒,我的节点js app正在发出多个http请求。下面是相同的示例代码。

首先,我从浏览器调用getAPI函数。 getApi函数调用getAccessToken API后,收到了accessstoken,我正在调用testApi。现在,如果testApi响应延迟20秒,则再次调用getAccessToken Api。我不想使用诺言。任何人都可以指出我在这里错过或做错了吗?

shttp = require('http-https');  

exports.getAPI = function(typeObj, request, response, callback) {
var userConf; //contains info such as port, host, url etc

_this.getAccessToken(function(tokenResponse) {
    var tokenInfo = JSON.parse(tokenResponse);
    var accessToken = JSON.parse(tokenInfo.response);
    accessToken = accessToken.access_token;
   if(accessToken) {
    _this.testApi(userConf,accessToken,function(sjmResponse) {
        callback(sjmResponse);
    }
   } else {
     callback(JSON.stringify({"payLoad":null,"reasonCode":"fail","status":null}));
   }
});
};


exports.getAccessToken = function(cb) {
    var tokenConf;  //contains info such as port, host, url etc
    var httpReq = shttp.request(tokenConf, function(res) {
        res.setEncoding('utf8');
        if (res.statusCode == 200) {
            var body = "";
            res.on('data', function (result) {
                body += result;
            });

            res.on('end', function (){
                cb(JSON.stringify({error: '', response: (body)}));
            });
        } else {
            cb(JSON.stringify({error: 'Failed to get user access token '+res.statusCode, response:''}));
        }
    });

    httpReq.on('error', function(e) {
        cb(JSON.stringify({error: 'Failed to get user access token'+e, response:''}));
    });

    httpReq.end();
};


exports.testApi = function(userConf,accessToken,sjmCallback) {
    var userConf; //contains info such as port, host, url etc
    var httpSubmitReq = shttp.request(userConf, function(res) {
        res.setEncoding('utf8');
        if (res.statusCode == 200) {
            var body = "";
            res.on('data', function (result) {
                body += result;
            });
            res.on('end', function () {
                sjmCallback(body);
            });
        } else {
            sjmCallback(JSON.stringify({"payLoad":null,"reasonCode":"fail","status":null}));

        }
    });

    httpSubmitReq.on('error', function(e) {
        sjmCallback(JSON.stringify({"payLoad":null,"reasonCode":"fail","status":null}));
    });

    httpSubmitReq.end();
};
app.get('/testApi', function (req, res) {
var typeObj = {};
typeObj.apiType= 'testApi';
    try {
        getAPI(JSON.stringify(typeObj), req, res, function(response) {
            res.end(response);
        });
    } catch(err) {
        res.end(err);
    }
});

0 个答案:

没有答案