【发布时间】:2020-02-10 06:36:11
【问题描述】:
我试图让fetchIDFromPerson 函数返回并将返回的值分配给ID,然后再执行fetchPersons 函数的其余部分。它只返回未定义,因为它是异步的。我该怎么做才能让它工作?
谢谢。
const fetchIDFromPerson = name => {
axios
.get(`https://swapi.co/api/people/?search=${name}&format=json`)
.then(response => extractImgIDFromURL(response.data.results[0].url))
.catch(error => console.error(error));
};
let body;
const fetchPersons = (query, imgID) => {
SWAPIGraphQL.post("", { query })
.then(result => {
const { allPersons } = result.data.data;
return (body = allPersons.map(person => {
const ID = fetchIDFromPerson(person.name); //This returns undefined!
return {
...person,
imgID: ID //needs to be assigned a value from fetchIDFromPerson
};
}));
})
.catch(error => console.error(error));
};
fetchPersons(GET_PERSONS_DATA);
【问题讨论】:
-
"它只返回 undefined,因为它是异步的。" - 不,它返回
undefined,因为你忘记了return你正在创建的承诺。 (在fetchPersons中相同,顺便说一句)
标签: javascript asynchronous promise fetch