Postman / pm api sendRequest 命令:如何在填充变量之前等待响应返回?

har*_*ant 6 javascript postman

我正在尝试使用邮递员的 pm api sendRequest 创建响应 json 的字典对象。

编写了一个递归函数来获取所有响应,但问题是响应字典对象填充甚至在响应返回之前就发生了。

有没有办法在收到每个相应的响应之前等待字典填充,以便在字典对象中捕获响应?

var respDictionary  = {};

getResponses (listOfUrls);

console.log("respDictionary: ");
console.log(respDictionary);

function getResponses(urlList) {

    if (typeof urlList === 'string') {
        urlList = urlList.split(' ');
    }
    _url = urlList[0];

    var call = {
        url: _url ,
        method: 'GET',
        header: {
            "Authorization": `Bearer ${token}`,
            "Content-Type": "application/json"
        }
    };
    urlList.splice(0, 1);

    pm.sendRequest(
        call,
        function (err, res) {
        if (err) {
            console.log(err);
        } else {
            if (urlList.length === 0) {
                return;
            }
            try {
                respDictionary[_url] = res.json();
            } catch (e) {
                console.log(err);
            }
            getResponses(urlList);
        }
    });
    console.log(respDictionary);
}
Run Code Online (Sandbox Code Playgroud)

输出是:

respDictionary:
Object:{}
//further, pm request responses are listed
Run Code Online (Sandbox Code Playgroud)

HMR*_*HMR 3

您不了解 JavaScript 异步处理。也许以下内容会有所帮助:

如果您使用承诺,您的代码将起作用:

function getResponses(urlList) {

  if (typeof urlList === 'string') {
    urlList = urlList.split(' ');
  }
  return Promise.all( 
    urlList.map(
      function(url){
        return {
          url: url ,
          method: 'GET',
          header: {
            //not sure where token comes from
            "Authorization": `Bearer ${token}`,
            "Content-Type": "application/json"
          }
        };
      }
    ).map(
      function(call){
        return new Promise(
          function(resolve,reject){
            pm.sendRequest(
              call,
              function (err, res) {
              if (err) {
                reject(err);
              } else {
                resolve([call.url,res.json()]);
              }
            });
          }
        )
        .then(
          undefined
          ,function(err){
            //if something goes wrong we will still return something
            return [call.url,{error:err}];
          }
        )
      }
    )
  )
  .then(
    function(results){
      return results.reduce(
        function(acc,result){
          acc[result[0]] = result[1];
        }
        ,{}
      );
    }
  )
}
getResponses (listOfUrls)
.then(//this will always succeed, failed items have {error:something}
  function(results){
    console.log("results:",results);
  }
);
console.log("this comes before results");
Run Code Online (Sandbox Code Playgroud)

上面的代码将导致所有请求同时发生,这可能不是所需的行为,我编写了一个节流方法,它是一些可能派上用场的库函数的一部分。您可以对代码应用限制,使其仅具有最大连接数:

const max = 10;//maximum 10 active connections
function getResponses(urlList) {  
  const throttled = throttle(max);
  if (typeof urlList === 'string') {
    urlList = urlList.split(' ');
  }
  return Promise.all( 
    urlList.map(
      function(url){
        return {
          url: url ,
          method: 'GET',
          header: {
            //not sure where token comes from
            "Authorization": `Bearer ${token}`,
            "Content-Type": "application/json"
          }
        };
      }
    ).map(
      throttled(//only max amount of connections active at any time
        function(call){
          return new Promise(
            function(resolve,reject){
              pm.sendRequest(
                call,
                function (err, res) {
                if (err) {
                  reject(err);
                } else {
                  resolve([call.url,res.json()]);
                }
              });
            }
          )
          .then(
            undefined
            ,function(err){
              //if something goes wrong we will still return something
              return [call.url,{error:err}];
            }
          )
        }
      )
    )
  )
  .then(
    function(results){
      return results.reduce(
        function(acc,result){
          acc[result[0]] = result[1];
        }
        ,{}
      );
    }
  )
}
getResponses (listOfUrls)
.then(//this will always succeed, failed items have {error:something}
  function(results){
    console.log("results:",results);
  }
);
console.log("this comes before results");
Run Code Online (Sandbox Code Playgroud)