Last active
June 7, 2024 11:48
-
-
Save chandra-prakash-meghwal/47642aea5ded9e2bd935626f61eae223 to your computer and use it in GitHub Desktop.
Javascript asynchronous and synchronous function calls
This file contains 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
async function fetchData1() { | |
// Simulate API 1 call (e.g., fetching data) | |
await new Promise((resolve) => setTimeout(resolve, 1000)); | |
return 'Data from API 1'; | |
} | |
async function fetchData2() { | |
// Simulate API 2 call (e.g., fetching data) | |
await new Promise((resolve) => setTimeout(resolve, 1500)); | |
return 'Data from API 2'; | |
} | |
async function mainAsync() { | |
const start = Date.now(); | |
const result1Promise = fetchData1(); | |
const result2Promise = fetchData2(); | |
const [result1, result2] = await Promise.all([result1Promise, result2Promise]); | |
const end = Date.now(); | |
console.log('Result from API 1:', result1); | |
console.log('Result from API 2:', result2); | |
console.log('Total execution time (async):', end - start, 'ms'); | |
} | |
function fetchData1Sync() { | |
// Simulate API 1 call (e.g., fetching data) | |
for (let i = 0; i < 1e7; i++) {} // Intentionally slow | |
return 'Data from API 1'; | |
} | |
function fetchData2Sync() { | |
// Simulate API 2 call (e.g., fetching data) | |
for (let i = 0; i < 2e7; i++) {} // Intentionally slower | |
return 'Data from API 2'; | |
} | |
function mainSync() { | |
const start = Date.now(); | |
const result1 = fetchData1Sync(); | |
const result2 = fetchData2Sync(); | |
const end = Date.now(); | |
console.log('Result from API 1:', result1); | |
console.log('Result from API 2:', result2); | |
console.log('Total execution time (sync):', end - start, 'ms'); | |
} | |
// calling functions asynchronously will take 1500 ms instead of timeout sum 1000+1500 = 2500 ms | |
mainAsync(); | |
// calling functions synchronously | |
mainSync(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment