兑现承诺

时间:2020-05-12 12:59:55

标签: javascript promise fetch

我有一个项目数组和一个日期数组,然后是映射日期,然后是项目,我正在对报告URL进行API调用 如果数据存在并且我收到了URL,我需要使用URL和项目的相应名称-日期来收集对象数组 在我当前的代码中,我收到带有承诺的对象数组...

  const getURL = async url => {
    try {
      await fetch(url, {method: 'GET', headers: headers_data})
        .then(response => response.json())
        .then(data => data.urls[0]);
    } catch (error) {
      console.log('Error getting links', error);
    }
  };
 let linksToDownload = [];
 await Promise.all(dateOfReport.map(async (date) => {
     await Promise.all(apps.map(async (appId) => {
      const API = process.env.API + appId + "&date=" + date ;
      let url = getURL(API)
      let obj = {
        name: date + "appId" + appId,
        value: url,
      }
      return linksToDownload.push(obj);
    }));
    return;
  }));

  console.log(linksToDownload);

我当前的日志是

[
  { name: '2020-04-29appIdda555', value: Promise { <pending> } },
  { name: '2020-04-29appIdqqq444', value: Promise { <pending> } },
  { name: '2020-04-30appIdda555', value: Promise { <pending> } },
  { name: '2020-04-30appIdqqq444', value: Promise { <pending> } }
]

预先感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您只是在等待一个等待而已

let url = getData(API);

–应该是

let url = await getData(API);

我可能会重构这样的东西:

// Simply get some JSON from an URL.
async function getJSON(url) {
  const resp = await fetch(url, { method: "GET", headers: headers_data });
  const data = await response.json();
  return data;
}

// Get the first report URL for a given app ID and date.
// TODO: error handling is missing
async function getReportURL(appId, date) {
  const apiUrl = process.env.API + appId + "&date=" + date;
  const data = await getJSON(apiUrl);
  const url = data.urls[0];
  return {
    name: date + "appId" + appId,
    value: url,
  };
}

// Iterate over date and app arrays to get an array of promises...
const linkPromises = [];
dateOfReport.forEach(date => {
  apps.forEach(appId => {
    // NB: not using `await` here, so the requests will
    //     happen in parallel here.
    linkPromises.push(getReportURL(appId, date));
  });
});

// Await all the promises to get the final result.
const links = await Promise.all(linkPromises);

console.log(links);