如何在变量内显示我的承诺数据?
我想存储一个从承诺中返回的对象。
我使用然后
和catch
获取对象,但是当我记录对象的结果时,获取undefined
。
这是我的代码:
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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当在承诺上使用
。然后使用
时,您的回调不会立即被调用。特别是,函数调用.then()
将继续执行,以便在函数稍后出现的行将在您的回调之前执行。在您的示例中,对
allstudents
的分配直到回调执行才会发生,直到您尝试使用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 withconsole.log(allStudents)
.In order to wait for the promise to resolve before continuing your execution, you could use
await
instead: