I have a problem, I tried to use async function to make API call but then() doesn't wait until the async function return the promise.
async function :
async function FgetFloorplansByFolder (idProject,idFolder, data = [], hasMore = false, lastSyncedAt = null) {
axios.get(API_URL, {
params:{
'last_synced_at':lastSyncedAt
},
headers: {
'Authorization': API_TOKEN,
'Accept': 'application/json'
}
})
.then((response) => {
let XHasMore = response.headers['x-has-more'];
let lastSyncedAt = response.headers['x-last-synced-at'];
for(var i in response.data) {
if(response.data[i].folder_id != null || response.data[i].folder_id == idFolder){
data.push(response.data[i])
}
}
if(XHasMore == 'true'){
FgetFloorplansByFolder(idProject,idFolder, data, XHasMore, lastSyncedAt)
}
else {
console.log(data);
return data
}
})
.catch((err) => {
return Promise.reject(err)
})
}
call of async function :
await FgetFloorplansByFolder(req.params.idProject, req.params.idFolder)
.then((result) => {
console.log(result);
})
.catch((error)=>{
console.log(error);
})
The expected result is : then function in the call wait until getFloorplansByFolders finish his recursive call and return data before print result in then. But then is printing undefined and doesn't wait until async function finish his call.
How can I do ?
awaitand.then()FgetFloorplansByFolderdoesn't return theaxios.get()result, so nothing else will wait for that call to complete nor would you get the response.response.dataan array? If so,for-inisn't the right tool to use to loop through it. More in this answer.