How to return response from an asynchronous call?

n JavaScript, asynchronous calls, like those made with AJAX, do not return values directly because the code execution continues without waiting for the asynchronous operation to complete. Instead, you must handle the response using callbacks, Promises, or async/await.

Here’s how to handle asynchronous responses properly in JavaScript:
1. Using Callbacks

A callback is a function passed as an argument to another function, to be executed once the asynchronous operation completes.

function fetchData(url, callback) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function () {
if (xhr.status === 200) {
callback(null, xhr.responseText); // Success
} else {
callback(new Error('Failed to fetch data')); // Error
}
};
xhr.onerror = function () {
callback(new Error('Network Error'));
};
xhr.send();
}

// Usage
fetchData('https://jsonplaceholder.typicode.com/posts/1', function (err, data) {
if (err) {
console.error('Error:', err.message);
} else {
console.log('Data:', JSON.parse(data));
}
});

2. Using Promises

A Promise represents a value that will be available in the future. You can use .then() and .catch() to handle the result of an asynchronous operation.

function fetchData(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function () {
if (xhr.status === 200) {
resolve(xhr.responseText); // Success
} else {
reject(new Error('Failed to fetch data')); // Error
}
};
xhr.onerror = function () {
reject(new Error('Network Error'));
};
xhr.send();
});
}

// Usage
fetchData('https://jsonplaceholder.typicode.com/posts/1')
.then(data => {
console.log('Data:', JSON.parse(data));
})
.catch(err => {
console.error('Error:', err.message);
});

3. Using async/await

The async/await syntax allows you to write asynchronous code in a synchronous style, making it more readable and easier to manage.

async function fetchData(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Failed to fetch data');
}
return await response.json();
}

// Usage
(async () => {
try {
const data = await fetchData('https://jsonplaceholder.typicode.com/posts/1');
console.log('Data:', data);
} catch (err) {
console.error('Error:', err.message);
}
})();

Which Approach to Use?

  1. Callbacks: Use for simple cases or legacy codebases but avoid for complex logic due to “callback hell.”
  2. Promises: Use for modern JavaScript where you need structured chaining of asynchronous operations.
  3. Async/Await: Preferred for cleaner and more readable code, especially when handling multiple asynchronous operations in sequence.

Example Using jQuery AJAX

If you’re using jQuery, AJAX operations return a Promise, so you can use .done()/.fail() or async/await.

function fetchData(url) {
return $.ajax({
url: url,
method: 'GET'
});
}

// Usage with Promises
fetchData('https://jsonplaceholder.typicode.com/posts/1')
.done(data => {
console.log('Data:', data);
})
.fail(err => {
console.error('Error:', err);
});

// Usage with async/await
(async () => {
try {
const data = await fetchData('https://jsonplaceholder.typicode.com/posts/1');
console.log('Data:', data);
} catch (err) {
console.error('Error:', err);
}
})();

No images available.