Last active
July 21, 2018 21:09
-
-
Save mpcen/bafd05ef99fe20d3ccf69dee9d63e2fc to your computer and use it in GitHub Desktop.
Promise.all with Async/Await vs only Async/Await
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 getMetric1Data() { | |
// Some API call that takes 500ms to fetch data | |
return new Promise(resolve => { | |
setTimeout(() => { | |
resolve("Got metric 1 data"); | |
}, 500); | |
}); | |
} | |
function getMetric2Data() { | |
// Some API call that takes 1000ms to fetch data | |
return new Promise(resolve => { | |
setTimeout(() => { | |
resolve("Got metric 2 data"); | |
}, 1000); | |
}); | |
} | |
function getMetric3Data() { | |
// Some API call that takes 500ms to fetch data | |
return new Promise(resolve => { | |
setTimeout(() => { | |
resolve("Got metric 3 data"); | |
}, 500); | |
}); | |
} | |
// Fetching the data using only Async/Await | |
(async () => { | |
const startTime = Date.now(); | |
const metric1Data = await getMetric1Data(); | |
const metric2Data = await getMetric2Data(); | |
const metric3Data = await getMetric3Data(); | |
const dataSet = [metric1Data, metric2Data, metric3Data]; | |
console.log("Data set from only async/await:", dataSet); | |
const endTime = Date.now(); | |
console.log(`Only Async/Await Process took: ${endTime - startTime}ms`); | |
})(); | |
// Fetching the data using Promise.all w/ Async/Await | |
(async () => { | |
const startTime = Date.now(); | |
const metric1Data = getMetric1Data(); | |
const metric2Data = getMetric2Data(); | |
const metric3Data = getMetric3Data(); | |
const dataSet = await Promise.all([metric1Data, metric2Data, metric3Data]); | |
console.log("Data set from Promise.all w/ async/await:", dataSet); | |
const endTime = Date.now(); | |
console.log( | |
`Promise.all w/ Async/Await Process took: ${endTime - startTime}ms` | |
); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment