I want to store an object returned from a promise inside a variable.
I used then
and catch
to get the object but when I log the result of my object getting undefined
.
Here is my code :
let allStudents;
const getStudents = async () => {
try {
const response = await Axios.get('/api/v1/student/')
return response
} catch (error) {
console.error(error);
}
}
let gsk = getStudents().then((res) => {
allStudents = res.data
return allStudents
}).catch((err) => {
console.log(err);
})
console.log(allStudents)
When using .then()
on a promise, your callback is not going to be called right away. In particular, the function calling .then()
will continue to execute, such that lines that come later in the function will be executed before your callback.
In your example, the assignment to allStudents
does not happen until the callback executes, and this is not going to happen until after you have already tried to print out the value with console.log(allStudents)
.
let gsk = getStudents().then((res) => {
// this code not executed until getStudents() complete
allStudents= res.data
return allStudents
})
// this code is executed before getStudents() completes
console.log(allStudents)
In order to wait for the promise to resolve before continuing your execution, you could use await
instead:
let res = await getStudents(); // do not continue until getStudents() completes
allStudents = res.data;
console.log(allStudents);