首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Axios console.log数据但返回Promise <pending>

Axios console.log数据但返回Promise <pending>
EN

Stack Overflow用户
提问于 2021-08-26 19:22:16
回答 3查看 824关注 0票数 0

我试图检索数据,但我无法返回它,只能在控制台中看到它,这是一个简单的axios get函数,但由于某些原因,即使在使用async/await之后,我仍然得到了承诺。

我的目标是将数据保存到内存中。

任何帮助都将不胜感激

代码语言:javascript
运行
复制
    let fetchTodo = async () => {
    
        await axios.get('https://jsonplaceholder.typicode.com/todos/1')
            .then(res => console.log(res.data))
            .then(res => { return res })
            .catch(err => console.log(err))
    };

console.log("TEST: ", fetchTodo())

console

EN

回答 3

Stack Overflow用户

发布于 2021-08-26 19:36:25

Asycn函数总是返回一个promise,要从fetchTodo函数获取数据,您需要创建另一个等待fetchTodo()返回结果的异步函数。如果您正在使用react,则可以在fetchTodo函数的.then链中使用状态并更新状态。

票数 0
EN

Stack Overflow用户

发布于 2021-08-26 19:53:56

async/await语法意味着函数将返回一个Promise

如果你想返回值,你可以这样做:

代码语言:javascript
运行
复制
let fetchTodo = async () => {
  try {
    const res = await axios.get("https://jsonplaceholder.typicode.com/todos/1");
    return res;
  } catch (error) {
    console.log(error);
  }
};

// For the folowing code to work, it must be placed inside a async  function as well
const res = await fetchTodo();
console.log(`Test: ${res.data}`);

// If it's a Top level call, use the folowing code
const res = fetchTodo().then( res => {
    const data = res.data;
    // The rest of your code goes here.
    // ...
    // ...
    // ...
}).catch( error => {
    console.log(error);
});

有关它的更多信息,请访问:How can I use async/await at the top level?

票数 0
EN

Stack Overflow用户

发布于 2021-08-26 22:07:16

Asycn函数总是返回一个promise。为了获取或保存数据,您需要从.then()函数中获取数据。您可以在这里查看示例。希望它能对你有所帮助。

代码语言:javascript
运行
复制
let fetchTodo = async () => {
        await axios.get('https://jsonplaceholder.typicode.com/todos/1')
            .then(res => console.log(res.data))
            .then(res => { 
                  // here you can performance your task, save data, send 
                  // response or anything else
                  return res 
             })
            .catch(err => console.log(err))
           };

fetchTodo()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68944283

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档