无法在地图循环中访问 Axios 调用的值

kil*_*kis 2 javascript ecmascript-6 axios

我有一个 javascript 对象,其 ID 对应于一组画廊。我使用地图循环遍历它。在每个循环中,我都会进行 axios 调用来获取当前 id 的图库。

最后,我需要一个包含所有画廊内容的数组。

问题是地图循环完成后我无法访问数据。当我 console.log(gallery) 时,我看到了所有数据,但当我执行 console.log(galleries[0].gallery) 时,我看不到所有数据。

我怀疑这必须与异步调用有关。我是新手,所以我可能会错过一些简单的东西。

额外信息:这是一个 React Native 项目,带有 redux thunk。

请帮忙并谢谢你。

export function FetchGalleries( galleries_ids ) {

    return function (dispatch) {

        let galleries = [];
        galleries_ids.map( (record, index) =>
        {

            axios.get('https://e.dgyd.com.ar/wp-json/wp/v2/media?_embed&parent='+record.id)
              .then(response => {
                galleries.push( response );
              });

        });

        console.log(galleries); // I can see all data
        console.log( JSON.parse(JSON.stringify( galleries[0].gallery ))); // returns undefined
        dispatch({ type: FETCH_GALLERIES_SUCCESS, payload: galleries })

      }
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*a X 5

最简单的解决方案是等待所有承诺解决,然后处理结果

export function FetchGalleries( galleries_ids ) {

    return function (dispatch) {
        return Promise.all(galleries_ids.map( (record, index) => {
            return axios.get('https://e.dgyd.com.ar/wp-json/wp/v2/media?_embed&parent='+record.id);
        })).then(galleries => {
            dispatch({ type: FETCH_GALLERIES_SUCCESS, payload: galleries });
        });
    }
}
Run Code Online (Sandbox Code Playgroud)