Skip to content

Instantly share code, notes, and snippets.

@NyaGarcia
Last active April 29, 2019 15:32
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 NyaGarcia/7a47881a46eefd147a5763cf0a79125b to your computer and use it in GitHub Desktop.
Save NyaGarcia/7a47881a46eefd147a5763cf0a79125b to your computer and use it in GitHub Desktop.
Using async await inside of Array.map()
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