【问题标题】:Return response from Axios and assign it to a variable从 Axios 返回响应并将其分配给变量
【发布时间】:2020-10-23 16:55:58
【问题描述】:

我正在尝试使用 Axios 完成一些简单的事情,但没有运气。我想从 Axios 调用中得到响应并将其分配给一个变量,然后在功能块之外对其进行下一步操作。

const axios = require("axios");
var posts;
(async () => {
  const allPosts = await axios.get("http://jsonplaceholder.typicode.com/posts");
  posts = allPosts;
})()
// do something with posts here

我知道因为 func 是异步的,所以我们首先到达 // do something with posts here,然后我们如何处理异步函数之外的响应

【问题讨论】:

    标签: javascript node.js http axios


    【解决方案1】:

    通常您会在接收到数据后立即将posts 分配给异步函数inside 的状态变量,这会触发重新渲染。或者你会调用一个 redux dispatch action 来设置 redux 中的值,redux 会更新 props。所以简而言之,这是通常的 React 方式:更新 state 或 props 以呈现视图,使用 componentDidUpdate 进行任何附加逻辑。例如:

    const axios = require("axios");
    var posts;
    (async () => {
      const allPosts = await 
      axios.get("http://jsonplaceholder.typicode.com/posts");
      posts = allPosts;
      this.setState({
        posts,
      })
    })()
    

    【讨论】:

    • 糟糕!你说的对!我没注意到他在使用 react!
    • 抱歉,标签错误。我需要将这段代码添加到 Node 函数中
    【解决方案2】:

    可以考虑使用回调函数,如下代码sn-p:

    const axios = require("axios");
    
    (async () => {
      const allPosts = await axios.get("http://jsonplaceholder.typicode.com/posts");
      someThingYouWantToDo(allPosts);
    })()
    
    const someThingYouWantToDo = (posts) => {
      console.log(posts);
    };
    

    【讨论】:

      【解决方案3】:

      鉴于这是节点,而不是原始标签建议的 React,它可能很简单:

      const axios = require("axios");
      var posts;
      await (async () => {
        const allPosts = await axios.get("http://jsonplaceholder.typicode.com/posts");
        posts = allPosts;
      })();
      // do something with posts
      

      【讨论】:

      • 我认为你不能在异步函数之外使用 await
      • 是的。虽然把它放在一个里面几乎总是微不足道的。
      猜你喜欢
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2017-09-19
      • 2022-01-06
      • 1970-01-01
      相关资源
      最近更新 更多