request.js回调不遵循脚本顺序

时间:2019-05-29 06:41:09

标签: javascript node.js

request()之后的console.log("result value: " + result);下面的代码中

const request = require('request');
//export func.
module.exports = {
  func: function(servURI, APIKey, sName) {
    var result = 0;
    var options = {
      url: servURI + sName,
      headers: {
        "Accept-Charset": "application/x-www-form-urlencoded; charset=UTF-8",
        "Token": APIKey,
        "Accept-Language": "en-US,en;q=0.9,ar;q=0.8",
        "User-Agent": "Baymax"
      }
    }

    function callback(error, response, body) {
      if (!error && response.statusCode == 200) {
        const info = JSON.parse(body);
        result = info.id;
        console.log("0result value: " + result);
      } else if (response.statusCode == 404) {
        console.log("return 000");
        result = 0;
      }
    }
    request(options, callback);
    console.log("result value: " + result);
    return result;
  }
}

日志:

2019-05-29T06:21:44.321738+00:00 app[worker.1]: result value: 0 
2019-05-29T06:21:44.325147+00:00 app[worker.1]: result value: 0
2019-05-29T06:21:44.972246+00:00 app[worker.1]: 0result value: YZEBzE2BWR74QdsvS8WupVdWujUI17oPYygOf4ppO-e3AN8
2019-05-29T06:21:44.988216+00:00 app[worker.1]: 0result value: YZEBzE2BWR74QdsvS8WupVdWujUI17oPYygOf4ppO-e3AN8

那是为什么?以及解决方法,因为该函数返回0而不是info.id

0 个答案:

没有答案