无法引用从内部提取响应中保存的数据,但外部提取数据显示正常

时间:2021-08-02 01:03:39

标签: javascript async-await nested fetch

我正在使用 2 个 api 调用(一个有员工姓名、id ..等,另一个 api 有员工社交媒体链接)来获取员工数据。

  1. 员工 API
{
  persons:[
    { name: "Jane" },
    { name: "Joe" },
    { name: "Jim" }
  ]
}
  1. 社交媒体 API
{
  name: "Joe",
  url: "http://fb.com/joeCool"
}

所以我必须为每个员工调用社交媒体 API 并将该数据保存到一个数组中:

[
 {name: "Jane", url: "http://instagram.com/janeIsBest"},
 {name: "Joe", url: "http://fb.com/joeCool"},
 {name: "Jim", url: "http://snapchat.com/jimBo"}
]

问题在于嵌套的 fetch 调用。我可以输出变量(api 响应被分配给这个变量)并显示所有员工信息,但是当我 console.log(employee.url) 它显示 undefined

javascript 看起来像这样

async function loadFullEmployeeInfo() {
  const employeesSocialMediaPath = 'https://somewhere.io/api/socialmedia/';
  const employeesApi = 'https://somewhere.io/api/employees';
  const response = await fetch(employeesApi)
    .then(response => response.json())
    .then(data => data.persons)
    .then(persons => {

      persons.map(async (person) => {
        person.url = await fetch(`${employeesSocialMediaPath}${employee.id}`).then(response => response.json()).then(data => data.url)
      })
      return persons;

    })
    .catch((error) => {console.log(`Error: ${error}`)})
  console.log(response);
  return response;
}

并且数据是这样保存的:

  const employeesInfo = await loadFullEmployeeInfo();

employeesInfo 稍后被引用,当我执行 console.log(employeesInfo) 时,它显示所有内容,包括 url,但是当我执行 console.log(employeesInfo.url) 时,它显示 undefined。任何解释(尤其是 ELI5)表示赞赏


编辑 想通了,除了必须返回 Promises.all(response) 之外,我还有错误的 array.map 语法

我应该这样做

  const response = await fetch(employeesApi)
    .then(response => response.json())
    .then(data => data.persons)
    .then(persons => {

      const nPersons = persons.map(async (person) => {
          await fetch(`${employeesSocialMediaPath}${employee.id}`)
          .then(response => response.json())
          .then(data => {person.url = data.url;})
          return person;
        })
      return nPersons;

    })
    .catch((error) => {console.log(`Error: ${error}`)});

  return Promise.all(response);

0 个答案:

没有答案