Last active
September 22, 2020 18:54
-
-
Save johntran/54ccd714fa6d539d8d70b57ad04cc1a3 to your computer and use it in GitHub Desktop.
ES7 multiple async/await functions in parallel execution.
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
//old: productReviews.js - lines 121 - 125 | |
async function productReviewsByProductAllGet(request, response) { | |
try { | |
const { productId } = request.params; | |
// get all reviews for a product id | |
const reviews = await productReviewsQuery.selectAllByProductId(productId); | |
const result = []; | |
// Loop from beginning of reviews array to reviews | |
for(let i = 0; i < reviews.length; i++) { | |
// get the account id from a single review, get the user info tied to account id | |
const user = await accountsQuery.selectByAccountId(reviews[i].accountId); | |
// add firstname and lastname to review object | |
reviews[i].firstName = user.firstName; | |
reviews[i].lastName = user.lastName; | |
result.push(reviews[i]); | |
} | |
response.status(200).json(result); | |
} catch (error) { | |
response.status(200).json({ error: 'No Results' }); | |
} | |
} | |
// refactored: first attempt | |
async function productReviewsByProductAllGet(request, response) { | |
try { | |
const { productId } = request.params; | |
const reviews = await productReviewsQuery.selectAllByProductId(productId); | |
/** async functions are generator functions that return a promise. | |
* Use promise.all to get users in parallel instead of one at a time | |
*/ | |
const result = await Promise.all(reviews.map(async (review) => { | |
const {firstName, lastName} = await accountsQuery.selectByAccountId(review.accountId); | |
return Object.assign({}, review, { firstName, lastName }) | |
})) | |
response.status(200).json(result); | |
} catch (error) { | |
response.status(200).json({ error: 'No Results' }); | |
} | |
} | |
// Final Solution | |
async function productReviewsByProductAllGet(request, response) { | |
try { | |
const { productId } = request.params; | |
const reviews = await productReviewsQuery.selectAllByProductId(productId); | |
const reviewPromises = reviews.map( | |
(review) => accountsQuery.selectByAccountId(review.accountId) | |
.then( | |
({firstName, lastName}) => Object.assign({}, review, { firstName, lastName }) | |
) | |
.catch (error => null) | |
) | |
const result = await Promise.all(reviewPromises) | |
response.status(200).json(result); | |
} catch (error) { | |
response.status(200).json({ error: 'No Results' }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like this solution as well. :) Thanks for sharing!