Node Js在for循环中获取请求并在对象中收集响应

Node Js get request in for loop and collect responses in an object

这里是 nodejs / meteorjs 新手, 我正在尝试在 for 循环中查询 api 并收集一个对象和 return 该对象中的所有响应。这是我的代码设置


const req = require('request');

const getallJira = (namespace, services) => {

  let allJiraResponses = {};

  for (let i in services) {
    let _serviceName = services[i];
    const options = {
      method: 'POST',
      url: 'https://jira/jira/rest/api/2/search',
      headers: {
        'Content-Type': 'application/json',
        Authorization: base64Auth,
        Accept: 'application/json',
      },
      body: JSON.stringify({
        jql: `NAMESPACE = ${namespace} AND labels = 'kind/promotion' AND (SERVICE_NAME =  '${_serviceName}' OR 'Service Name/Package Name' = '${_serviceName}')`,
        maxResults: 1000000,
        startAt: 0,
        fields,
      }),
    };

    request(options, function(error, response) {
      if (error) throw new Error(error);
      const jiraResponse = JSON.parse(response.body);
      allJiraResponses[_serviceName] = jiraResponse;
    });
  }

  return allJiraResponses;
};

然而,由于 request 的异步特性,最终的 allJiraResponses return 为空。我如何在对象中记录来自 jira API 的所有响应并将其 return 记录给 getallJira

的调用者

我认为你应该拆分成函数,这样更清楚

单个服务第一个拿到结果的

const  getJiraService = ( namespace, serviceName) => new Promise((resolve, reject) => {
   const options = {
      method: 'POST',
      url: 'https://jira/jira/rest/api/2/search',
      headers: {
        'Content-Type': 'application/json',
        Authorization: base64Auth,
        Accept: 'application/json',
      },
      body: JSON.stringify({
        jql: `NAMESPACE = ${namespace} AND labels = 'kind/promotion' AND (SERVICE_NAME =  '${serviceName}' OR 'Service Name/Package Name' = '${serviceName}')`,
        maxResults: 1000000,
        startAt: 0,
        fields,
      }),
    };

    request(options, function(error, response) {
      if (error) {
        resolve({serviceName, error});
        return;
      }
      const jiraResponse = JSON.parse(response.body);
      resolve({serviceName, jiraResponse})
    });

})

const getallJira =  async (namespace, services) => {
const results = await Promise.all(services.map(s => getJiraService(namespace, s));
return results.reduce((res, {serviceName, error, jiraResponse}) => {
  if(!!jiraResponse){
    return {
      ...res,
      serviceName:  jiraResponse
    };
  }
  return res;

}, {})