0
我正在迭代数组并为每个项目进行REST API调用,但我在js的异步性质方面遇到了问题。我试图使用异步/等待,但我不认为我正确设置它,因为它不会等待响应并返回未定义。在回路中等待API响应
onSearchSuccess = async (response) => {
const persons = response._embedded.persons_search_collection;
const personsWithClasses = await persons.reduce(
(acc, person) => {
const params = {
person_id: person.person_id,
date: '2017-01-05',
enrollment_status: 3,
class_status: 2,
};
return getClasses(//this function does an GET request and returns the response
params,
(classesResponse) => {
const { classes } = classesResponse._embedded;
console.log(classes); //logs after the console.log below
return [...acc, { ...person, classes }];
},
() => acc,
);
}, []);
console.log(personsWithClasses); //return undefined
}
export const getClasses = (params, success, error) => {
axios.get(`${uri}/classes`, { params })
.then(({ data }) => {
success(data);
})
.catch(err => error(err));
};
如果'getClasses'类返回一个promise,那么你不能'[... acc]'因为'acc'将是一个承诺。你为什么在这里使用'reduce'?你究竟想要达到什么样的目标?你想要依次执行所有的REST吗?或者干脆等到所有请求都完成了? –
基本上我有一个人的阵列,我正在做一个请求,以获得每个人的课程,如果有那天的课程,然后返回一个对象与人和人的类,否则只是返回累加器并继续前进。我基本上想要过滤掉没有类的人,并返回一个新的对象与人的属性和类,如果他们这样做。 –
如果我提供'getClasses'的代码会有帮助吗? –