Skip to content

Instantly share code, notes, and snippets.

@patmigliaccio
Created April 4, 2019 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patmigliaccio/94a6d4f2b175df05fc6cf50617e96998 to your computer and use it in GitHub Desktop.
Save patmigliaccio/94a6d4f2b175df05fc6cf50617e96998 to your computer and use it in GitHub Desktop.
patmigliaccio.com/resolving-nested-promises 4/4/19
function resolveUsers(users) {
const resolveComments = createCommentsResolver();
return Promise.all(
users.map(user => {
return resolveComments(user)
})
);
}
/**
* Creates a `resolveComments` function which retrieves the full
* comments for the specified user and caches the comment request
* if it has already been made.
*
* @returns {Function} `resolveComments`
*/
function createCommentsResolver() {
let cache = {};
return async function resolveComments(user) {
// Retrieves all comments based on `commentId`.
user.comments = await Promise.all(
user.commentIds.map(commentId => {
// Adds comment to cache, if it doesn't already exist.
if (!cache[commentId]) {
cache[commentId] = comments.getCommentById(commentId)
}
return cache[commentId]
})
);
return user;
}
}
const activeUsers = await post.getActiveUsers();
const resolvedUsers = await resolveUsers(activeUsers);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment