This content was released on Dec 6 2016. The official support period is 6-months
from this date.
Learn how to wrap a synchronous function to make it asynchronous, and how to handle simple use cases — a chain of synchronous tasks and a collection of similar independent tasks.
Here’s an overview of how you can wrap synchronous functions to make them asynchronous in JavaScript:
Wrap a Synchronous Function in a Promise (JavaScript)
One common method to convert a synchronous function to an asynchronous one is to use Promise. A Promise can represent the eventual completion (or failure) of an asynchronous operation and its resulting value.
Example:
javascript
Copy code
function syncFunction() {
// This function is synchronous
return “Hello, world!”;
}
// To make it asynchronous:
function asyncFunction() {
return new Promise((resolve, reject) => {
try {
let result = syncFunction(); // Call the synchronous function
resolve(result); // Resolve with the result
} catch (error) {
reject(error); // Reject with error if one occurs
}
});
}
asyncFunction().then(result => console.log(result)).catch(error => console.log(error));
2. Handling a Chain of Synchronous Tasks
If you have a chain of synchronous functions that need to be run sequentially, you can still use Promises to ensure they execute in order asynchronously.
Example:
javascript
Copy code
function task1() { return “Task 1 complete”; }
function task2() { return “Task 2 complete”; }
function task3() { return “Task 3 complete”; }
function asyncTaskChain() {
return new Promise((resolve, reject) => {
const results = ;
results.push(task1());
results.push(task2());
results.push(task3());
resolve(results);
});
}
asyncTaskChain().then(results => console.log(results));
3. Handling Independent Tasks Concurrently
When you have a collection of independent tasks that can run concurrently (i.e., they don’t depend on each other), you can use Promise.all() to execute them in parallel and wait for all of them to complete.
Example:
javascript
Copy code
function task1() {
return new Promise(resolve => setTimeout(() => resolve(“Task 1 complete”), 1000));
}
function task2() {
return new Promise(resolve => setTimeout(() => resolve(“Task 2 complete”), 500));
}
function task3() {
return new Promise(resolve => setTimeout(() => resolve(“Task 3 complete”), 1500));
}
]
});
Best Regards
merry678