Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update 3-promise-all.js #329

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 35 additions & 5 deletions 02-async-js/hard (promises)/3-promise-all.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,47 @@


function waitOneSecond() {

return new Promise((resolve) => {
setTimeout(() => {
console.log("Resolved after 1 second");
resolve();
}, 1000);
});
}

function waitTwoSecond() {

return new Promise((resolve) => {
setTimeout(() => {
console.log("Resolved after 2 seconds");
resolve();
}, 2000);
});
}

function waitThreeSecond() {

return new Promise((resolve) => {
setTimeout(() => {
console.log("Resolved after 3 seconds");
resolve();
}, 3000);
});
}

function calculateTime() {
async function calculateTime() {
const startTime = Date.now(); // Record the start time

// Execute each function sequentially
// await waitOneSecond();
// await waitTwoSecond();
// await waitThreeSecond();

// Excutes each function using Promise.all

await Promise.all([waitOneSecond(),waitTwoSecond(),waitThreeSecond()]);

const endTime = Date.now(); // Record the end time
const elapsedTime = endTime - startTime; // Calculate elapsed time in milliseconds
console.log(`Total time waited: ${elapsedTime / 1000} seconds`);
}

}
calculateTime(); // Call calculateTime function to demonstrate