我正在使用 2 个 api 调用(一个有员工姓名、id ..等,另一个 api 有员工社交媒体链接)来获取员工数据。
{
persons:[
{ name: "Jane" },
{ name: "Joe" },
{ name: "Jim" }
]
}
{
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);