To return the response from an asynchronous call in JavaScript, you have a few options depending on the specific context and requirements of your code. Here are three common approaches:
- Using a callback function:
function doAsyncCall(callback) {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => {
const result = data.title;
callback(result);
})
.catch(error => console.error(error));
}
doAsyncCall((result) => {
console.log(result); // Output: delectus aut autem
});
In this example, doAsyncTask
makes a dummy API call using the fetch
function. When the API returns a response, it is converted to JSON using the json
method and the callback function is called with the title of the first to-do item.
- Using Promises:
function doAsyncCall() { return fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .then(data => { const result = data.title; return result; }) .catch(error => console.error(error)); } doAsyncCall() .then((result) => { console.log(result); // Output: delectus aut autem }) .catch((error) => { console.error(error); });
In this example, doAsyncTask
returns a Promise that makes a dummy API call using the fetch
function. When the API returns a response, it is converted to JSON using the json
method and the Promise is resolved with the title of the first to-do item.
- Using async/await:
async function doAsyncCall() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
const result = data.title;
return result;
} catch (error) {
console.error(error);
}
}
async function check() {
try {
const result = await doAsyncCall();
console.log(result); // Output: delectus aut autem
} catch (error) {
console.error(error);
}
}
check();
In this example, doAsyncTask
is an asynchronous function that makes a dummy API call using the fetch
function. When the API returns a response, it is converted to JSON using the json
method and the title of the first to-do item is returned. In the main
function, you use the await
keyword to wait for the Promise to be resolved before moving on to the next line of code. You also need to use a try/catch block to handle any errors that may occur during the async operation.