Created
April 4, 2019 20:05
-
-
Save patmigliaccio/94a6d4f2b175df05fc6cf50617e96998 to your computer and use it in GitHub Desktop.
patmigliaccio.com/resolving-nested-promises 4/4/19
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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