Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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. Process takes ~2000ms
- (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. Process takes ~1000ms
- (async () => {
- const startTime = Date.now();
- const dataSet = await Promise.all([
- getMetric1Data(),
- getMetric2Data(),
- getMetric3Data()
- ]);
- console.log("Data set from Promise.all w/ async/await:", dataSet);
- const endTime = Date.now();
- console.log(
- "Promise.all with Async/Await Process took: " +
- (endTime - startTime) +
- " ms"
- );
- })();
Add Comment
Please, Sign In to add comment