Asynchronous JavaScript Concepts
1. Synchronous vs. Asynchronous Code
Synchronous Example:
[Link]('Start');
[Link]('End');
Asynchronous Example:
[Link]('Start');
setTimeout(() => [Link]('Async Task'), 1000);
[Link]('End');
2. Patterns for Dealing with Asynchronous Code
Common patterns include callbacks, Promises, and async/await.
Example with setTimeout:
function asyncTask(callback) {
setTimeout(() => {
callback('Task Complete');
}, 1000);
asyncTask(result => [Link](result));
3. Callbacks
function fetchData(callback) {
setTimeout(() => {
callback('Data fetched');
}, 1000);
fetchData((data) => {
[Link](data);
});
4. Callback Hell
getUser(1, (user) => {
getRepositories([Link], (repos) => {
getCommits(repos[0], (commits) => {
[Link](commits);
});
});
});
// Functions simulating async behavior
function getUser(id, callback) { setTimeout(() => callback({ id, name: 'John' }), 1000); }
function getRepositories(name, callback) { setTimeout(() => callback(['repo1', 'repo2']), 1000); }
function getCommits(repo, callback) { setTimeout(() => callback(['commit1']), 1000); }
5. Named Functions to Rescue
function handleCommits(commits) {
[Link](commits);
function handleRepositories(repos) {
getCommits(repos[0], handleCommits);
function handleUser(user) {
getRepositories([Link], handleRepositories);
getUser(1, handleUser);
6. Promises
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('Data fetched'), 1000);
});
fetchData().then(data => [Link](data));
7. Replacing Callbacks with Promises
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => resolve('Data fetched'), 1000);
});
fetchData().then((data) => [Link](data));
8. Consuming Promises
fetchData().then(data => [Link](data)).catch(err => [Link](err));
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('Data fetched'), 1000);
});
9. Creating Settled Promises
// Already resolved and rejected Promises
const resolvedPromise = [Link]('Resolved Data');
const rejectedPromise = [Link](new Error('Rejected Data'));
[Link](data => [Link](data));
[Link](err => [Link](err));
10. Running Promises in Parallel
const p1 = new Promise(resolve => setTimeout(() => resolve('Task 1'), 1000));
const p2 = new Promise(resolve => setTimeout(() => resolve('Task 2'), 2000));
[Link]([p1, p2]).then(results => [Link](results)); // ['Task 1', 'Task 2']
11. Async and Await
async function fetchData() {
const data = await new Promise(resolve => setTimeout(() => resolve('Data fetched'), 1000));
[Link](data);
fetchData();