使用React Native和Redux,我正在尝试首先获取一些帖子,然后获取相应的作者。
我面对两个问题:
catch
和then
语句的顺序?我想说的是:如果无法获取帖子,则发送失败操作,停止,不做任何其他操作(即,不尝试获取作者)。但是,如果帖子被成功获取,请继续获取作者。posts
传递给fetchAuthorsForPostsFromAPI
?按原样,fetchAuthorsForPostsFromAPI
.中的posts
是undefined
// 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 ) ) );
}
发布于 2018-10-15 01:35:50
有几种方法可以解决这个问题。我使用async/await比promise简单得多。
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;
}
}
https://stackoverflow.com/questions/52802040
复制相似问题