Example 1:
As we can see from the output, all three sleep functions run and they print out how long they have run for. We can also see how long the main function has run, just over 3000ms. This shows that we are running these tasks in parallel, if we weren't, the main function would have run for about 6000ms.main.js
async function sleep(time = 1) {
const sleepMilliseconds = time * 1000
return new Promise(resolve => {
setTimeout(() => {
resolve(`Slept for: ${sleepMilliseconds}ms`)
}, sleepMilliseconds)
})
}
async function main() {
// 1.
console.time('main')
// 2.
const [firstCall, secondCall, thirdCall] = await Promise.all([
sleep(1),
sleep(2),
sleep(3)
])
console.log(`First call: ${firstCall}`)
console.log(`Second call: ${secondCall}`)
console.log(`Third call: ${thirdCall}`)// 3.
console.timeEnd('main')
}main();
Example 2: Axios with async-await
main.jsimport axios from 'axios';
async function fetchData(url: string) {
try {
const response = await axios.get(url);
return response.data;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
}
async function parallelRequests(urls: string[]) {
try {
const promises = urls.map(url => fetchData(url));
const results = await Promise.all(promises);
console.log(results);
} catch (error) {
console.error('Error with parallel requests:', error);
}
}
const urls = [
'https://jsonplaceholder.typicode.com/users/1',
'https://jsonplaceholder.typicode.com/users/2',
'https://jsonplaceholder.typicode.com/users/3'
];
parallelRequests(urls);Example 3: Axios with async-await-Promise
main.jsconst axios = require('axios');
function fetchData(url: string) {
return new Promise((resolve, reject) => {
axios.get(url)
.then((response: { data: unknown; }) =>
resolve(response.data))
.catch((error: any) => {
console.error('Error fetching data:', error);
reject(error);
});
});
}
function parallelRequests(urls: string[]) {
const promises = urls.map(url => fetchData(url));Promise.all(promises)
.then(results => {
console.log(results);
})
.catch(error => {
console.error('Error with parallel requests:', error);
});
}
const urls = [
'https://jsonplaceholder.typicode.com/users/1',
'https://jsonplaceholder.typicode.com/users/2',
'https://jsonplaceholder.typicode.com/users/3'
];
parallelRequests(urls);