'How to get return value of a Promise<Array[]> from an Async-Await Function?
Im trying to get the return value of an async-await function but im not getting the value i need.
const filterStuff = async (filters) => {
//some code here
await client<StuffPagination>(endpoint,body)
.then((stuffresult)=>{
const {stuff,page} = stuffresult;
let fiteredStuff as Stuff[] = stuff;
console.log(filteredStuff);
return filteredStuff;
})
.catch(()=>{
//do something
})
.finally(()=>{
//do something
});
};
How do i get the actual return value Stuff[] of the async-await function outside of the function? I have tried using .then to get the data but log for the data is always undefined while the console.log(filteredStuff) that im returning has a value. Is there something im missing?
useEffect(() => {
filterStuff(BaseFilters).then((data) => {
console.log(data);
});
}, []);
Solution 1:[1]
You are not returning at required place. Please see below updated code which await for the response.
const filterStuff = async (filters) => {
try {
//some code here
const stuffresult = await client<StuffPagination>(endpoint,body);
const {stuff,page} = stuffresult;
let fiteredStuff as Stuff[] = stuff;
console.log(filteredStuff);
return filteredStuff;
}
catch {
//do something
}
finally {
//do something
}
};
Solution 2:[2]
you are missing a return statement in you filterStuff function
const filterStuff = async (filters) => {
//some code here
return client<StuffPagination>(endpoint,body)
.then((stuffresult)=>{
const {stuff,page} = stuffresult;
let fiteredStuff as Stuff[] = stuff;
console.log(filteredStuff);
return filteredStuff;
})
.catch(()=>{
//do something
})
.finally(()=>{
//do something
});
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user1672994 |
| Solution 2 | R4ncid |
