2017-03-01 64 views
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)); 
}; 
+0

如果'getClasses'类返回一个promise,那么你不能'[... acc]'因为'acc'将是一个承诺。你为什么在这里使用'reduce'?你究竟想要达到什么样的目标?你想要依次执行所有的REST吗?或者干脆等到所有请求都完成了? –

+0

基本上我有一个人的阵列,我正在做一个请求,以获得每个人的课程,如果有那天的课程,然后返回一个对象与人和人的类,否则只是返回累加器并继续前进。我基本上想要过滤掉没有类的人,并返回一个新的对象与人的属性和类,如果他们这样做。 –

+0

如果我提供'getClasses'的代码会有帮助吗? –

回答

1

正如我在评论中提到的,如果您调用异步函数,reduce将无法​​正常工作。您可以使用Promise.all.map为左右(我试图用async/await尽可能):

onSearchSuccess = async (response) => { 
    const persons = response._embedded.persons_search_collection; 
    let personsWithClasses = await Promise.all(persons.map(async (person) => { 
    try { 
     const classes = await getClasses({ 
     person_id: person.person_id, 
     date: '2017-01-05', 
     enrollment_status: 3, 
     class_status: 2, 
     }); 

     return {...person, classes}; 
    } catch(error) { 
     // ignore errors if a person wasn't found 
     return null; 
    } 
    })); 
    personsWithClasses = personsWithClasses.filter(x => x != null); 
    console.log(personsWithClasses); 
} 


export const getClasses = params => { 
    return axios.get(`${uri}/classes`, { params }); 
}; 

另外请注意我对getClasses所做的更改。无论如何,如果axios.get返回承诺,没有理由让它接受回调。

+0

的代码,谢谢!我忘了更新我使用的promise.all代码,但我正在接近。只是没有try/catch部分。 –