Efficiently Combine Sync and Async tasks with Promise.all
Promise.all with Mixed Operations:
Write a JavaScript program that combines synchronous and asynchronous tasks using Promise.all.
Solution-1: Using Named Functions
Code:
// A synchronous task that returns a value
function syncTask() {
return "Synchronous result";
}
// An asynchronous task that resolves after a delay
function asyncTask() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Asynchronous result");
}, 2000);
});
}
// Combine synchronous and asynchronous tasks using Promise.all
Promise.all([syncTask(), asyncTask()])
.then((results) => {
console.log("Results:", results); // Logs: ['Synchronous result', 'Asynchronous result']
})
.catch((error) => {
console.error("Error:", error); // Logs any errors if they occur
});
Output:
"Results:" ["Synchronous result", "Asynchronous result"]
Explanation:
- syncTask is a simple function that immediately returns a synchronous value.
- asyncTask is a function that returns a promise, resolving after 2 seconds.
- Both tasks are combined in an array passed to Promise.all.
- Promise.all waits until all tasks (both synchronous and asynchronous) complete.
- The then block logs an array of results, while the catch block handles any errors.
Solution-2: Inline Functions
Code:
// Combine synchronous and asynchronous tasks using Promise.all
Promise.all([
// Synchronous task executed inline
"Inline synchronous result",
// Asynchronous task executed inline
new Promise((resolve) => {
setTimeout(() => {
resolve("Inline asynchronous result");
}, 1500);
}),
])
.then((results) => {
console.log("Results:", results); // Logs: ['Inline synchronous result', 'Inline asynchronous result']
})
.catch((error) => {
console.error("Error:", error); // Logs any errors if they occur
});
Output:
"Results:" ["Inline synchronous result", "Inline asynchronous result"]
Explanation:
- The synchronous task is represented as a string literal directly in the array.
- The asynchronous task is a promise created inline using new Promise and setTimeout.
- Both tasks are passed to Promise.all, which resolves when all tasks are complete.
- The results of all tasks are logged in an array.
See the Pen promises-and-async-await-exercise-12 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: JavaScript Promises with setTimeout Examples.
Next: Create Debounced Functions in JavaScript with Promises.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics