Извлечение авторов постов и заказ обещаний с помощью Redux - PullRequest
0 голосов
/ 14 октября 2018

Используя React Native и Redux, я пытаюсь сначала получить несколько постов, а затем выбрать соответствующих авторов.

У меня две проблемы:

  1. Как я могу исправить порядок моих catch и then заявлений?Я хочу сказать: если сообщения не могут быть получены, отправьте действие сбоя, остановитесь и больше ничего не делайте (то есть не попытайтесь получить авторов).Но если сообщения были получены успешно, продолжайте и выбирайте авторов.
  2. Что мне нужно изменить в моем коде ниже, чтобы posts был передан fetchAuthorsForPostsFromAPI?Как есть, posts есть undefined в пределах fetchAuthorsForPostsFromAPI.

// fetches the posts from the API
export const fetchPostsFromAPI = () => ( dispatch ) => {

    // dispatch action: currently fetching posts from the API
    dispatch( fetchingPosts() );

    // prepare the promise that fetches the posts from the API
    let loadPosts = new Promise( ( resolve, reject ) => {
        // uses dummy data for now
        if( !postsInitial ) {
            reject( "Error: Could not get posts" );
        }
        else {
            resolve( postsInitial );
        }
    });

    // actually fetch the posts from the API
    return loadPosts
        // if error fetching the posts from the API
        .catch( error => dispatch( fetchPostsFailure( error ) ) )
        // if success fetching the posts from the API
        .then( posts => dispatch( fetchPostsSuccess( posts ) ) )
        // fetch authors for posts from the API
        .then( posts => fetchAuthorsForPostsFromAPI( posts, dispatch ) )
}

// is dispatched if the posts were succesfully fetched from the API
function fetchPostsSuccess( posts ) {
    return {
        type: PostConstants.FETCH_POSTS_SUCCESS,
        postsWithoutAuthors: posts,
    }
}

// is called when the posts have been fetched successfully from the API
// fetches the author for each post from the API
function fetchAuthorsForPostsFromAPI( posts, dispatch ) {

    console.log( "posts:", posts ); // logs "posts: undefined"

    // dispatch action: currently fetching authors of posts from the API
    dispatch( fetchingAuthorsForPosts() );

    // prepare the promise that fetches the authors for the posts from the API
    let loadAuthors = new Promise( ( resolve, reject ) => {

        // for each post
        posts.map( post => {

            // find the author by id
            const authorObj = authors.find( author => {
                return author.id === post.authorId
            });

            // if error finding author
            if( !authorObj ) {
                reject( "Error: Author for this id could not be found!" );
            }

            // if success finding author, keep going
            else {
                post.author = authorObj;
            }

        });

        // resolve
        resolve( posts );
    });

    // actually fetch the authors from the API
    return loadAuthors
        // if success fetching the authors for the posts from the API
        .then( posts => dispatch( fetchPostsAuthorsSuccess( posts ) ) )
        // if error fetching the authors for the posts from the API
        .catch( error => dispatch( fetchPostsAuthorsFailure( error ) ) );
}

1 Ответ

0 голосов
/ 14 октября 2018

Существует несколько способов решения проблемы.Imho использовать async / await намного проще, чем обещать.

    async const fetchData = () => (dispatch) =>  {
      var postResult = await getPosts(dispatch);
      if (postResult) {
        await getAuthors();
      }
    }

    const getPosts = async () => (dispatch) =>  {
      var apiResponse = await getPostsFromApi();
      if(apiResponse)
      {
        //dispatch something
        return true;
      } else {
        //dispatch error
        return false;
      }
    }
...