I want to return the response of axios but get the console.log as undefined.
getFirstPageData();
async function getFirstPageData() {
const res = await getPageData(1) ;
console.log("res--->", res);
}
async function getPageData(page_num){
let pageNum = page_num;
console.log("page_num" , pageNum);
let path = "https://......"
axios.get(path).then(
(response) => {
var result = response.data;
console.log(result);
return result;
},
(error) => {
console.log(error);
}
);
}
Is this a problem in await or async. any way returning this response.
CodePudding user response:
In light of my comment on your post and what you are trying to do.
Your getPageData
should return the promise from axios like the following.
function getPageData(page_num){
let pageNum = page_num;
console.log("page_num" , pageNum);
let path = "https://......"
return axios.get(path).then(
(response) => {
var result = response.data;
console.log(result);
return result;
},
(error) => {
console.log(error);
}
);
}
Loose the async from the function getPageData
since it is not an asynchronous function. it returns a promise that you will get data from in your const res = await getPageData(1) ;
CodePudding user response:
You'll need to return the promise that axios.get()
returns, this will keep the promise chain intact.
I would also suggest throwing in the reject handler to propagate any error to the top level, again keeping the chain intact.
getFirstPageData();
async function getFirstPageData() {
try {
const res = await getPageData(1) ;
console.log("res--->", res);
} catch (error) {
console.error('An error occurred:', error);
}
}
async function getPageData(page_num){
let pageNum = page_num;
console.log("page_num" , pageNum);
let path = "https://......"
return axios.get(path).then(
(response) => {
var result = response.data;
console.log(result);
return result;
},
(error) => {
console.error(error);
throw error;
}
);
}