Last active
April 29, 2019 15:32
-
-
Save NyaGarcia/7a47881a46eefd147a5763cf0a79125b to your computer and use it in GitHub Desktop.
Using async await inside of Array.map()
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
function getCalculatedRoutes(routes: Array<any>): Promise<any> { | |
return Promise.all( | |
routes.map(async (route: any) => { | |
const distance = await getDistance(); | |
route.distance = distance; | |
route.cost = calculateCost(distance); | |
return route; | |
}) | |
); | |
} | |
function calculateCost(distance: number): string { | |
return (distance * 0.19).toFixed(2); | |
} | |
async function getDistance() { | |
//simulating the API call | |
return Math.floor(Math.random() * 10) + 1; | |
} | |
async function printResults() { | |
const routes = await getCalculatedRoutes([{destination: "Malaga"}, {destination: "Barcelona"}]); | |
document.write(JSON.stringify(routes)); | |
} | |
printResults(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment