Last active
September 6, 2023 20:14
-
-
Save rimrachai-marma/511aed37ed50ec88299d55b6d5e6db7e to your computer and use it in GitHub Desktop.
async reduce
This file contains hidden or 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
async function asyncReduce(array, asyncReducerFunction, initialValue) { | |
let accumulator = initialValue; | |
for (const element of array) { | |
accumulator = await asyncReducerFunction(accumulator, element); | |
} | |
return accumulator; | |
} | |
// --- Example usage: --- // | |
const storeItems = [ | |
{ id: 1, qty: 2, price: 30 }, | |
{ id: 2, qty: 3, price: 50 }, | |
{ id: 3, qty: 5, price: 40 }, | |
]; | |
const cartItems = [ | |
{ id: 1, qty: 2 }, | |
{ id: 4, qty: 3 }, | |
{ id: 3, qty: 5 }, | |
]; | |
async function fetchProduct(id) { | |
// Simulate a network request, e.g., fetching data from an API | |
await new Promise((resolve) => setTimeout(resolve, 1000)); | |
return storeItems.find((storeItem) => storeItem.id === id); | |
} | |
async function main() { | |
const totalPrice = await asyncReduce(cartItems, async (total, cartItem) => { | |
const storeItem = await fetchProduct(cartItem.id); | |
return total + cartItem.qty * (storeItem?.price ?? 0); | |
}, 0); | |
console.log(totalPrice); | |
// Another way use async reduce with built in method | |
const totalPrice2 = await cartItems.reduce( async (totalPromise, cartItem) => { | |
const total = await totalPromise; | |
const storeItem = await fetchProduct(cartItem.id); | |
return total + cartItem.qty * (storeItem?.price ?? 0); | |
}, Promise.resolve(0)); | |
console.log(totalPrice2); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment