如何在变量内显示我的承诺数据?

发布于 2025-02-03 02:54:47 字数 672 浏览 3 评论 0原文

我想存储一个从承诺中返回的对象。

我使用然后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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没有心的人 2025-02-10 02:54:47

当在承诺上使用。然后使用时,您的回调不会立即被调用。特别是,函数调用.then()将继续执行,以便在函数稍后出现的行将在您的回调之前执行

在您的示例中,对allstudents的分配直到回调执行才会发生,直到您尝试使用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)

为了等待承诺在继续执行之前解决,您可以使用等待

let res = await getStudents(); // do not continue until getStudents() completes
allStudents = res.data;
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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文