【问题标题】:I can't return the response from axios request我无法从 axios 请求返回响应
【发布时间】:2020-07-07 10:28:48
【问题描述】:

我正在尝试在节点中创建一个模块以使用 axios 请求从 API 返回一个 json。但是当我尝试从函数getJson() 中返回响应时,什么都没有返回给我。

const axios = require('axios');
const authentication = require('./authentication');


const url = `https://api.codenation.dev/v1/challenge/dev-ps/generate-data?token=${authentication.token}`;

const getJson = async () => {
  const response = await axios.get(url);
  // Here i can see the json normally
  console.log(response.data)
  return response.data
}

const response = getJson()
// but here nothing is shows to me in console.
console.log(response)

return of console

【问题讨论】:

  • 你的 getJson 函数是一个 async 函数,这意味着它返回一个 Promise 实例。您必须等待另一个带有awaitasync 函数中的承诺,否则添加一个.then() 回调。

标签: javascript node.js console return axios


【解决方案1】:

getJson() 实际上是返回一个promise 实例。你只需要await就可以了:

(async () => {
  const response = await getJson()
  console.log(response)
})();

【讨论】:

    【解决方案2】:

    这是因为 const response = getJson()getJson 运行之前执行它的代码,因为它是异步的,并且响应在执行时没有到达该实例。

    # This code runs and executes some point in future when response arrives
    const getJson = async ()=>{
      const response = await axios.get(url);
      //Here i can see the json normally
      console.log(response.data)
      return response.data
    }
    
    # This code runs and executes immediately which doesn't have response yet
    const response = getJson()
    

    【讨论】:

    • 我明白了,托马斯!谢谢。在这种情况下,我是否需要执行另一个包装 const 的异步函数来强制等待 getJson() 的返回?
    • 是的,您将为它使用另一个异步函数,或者您可以使用 IIFE - 像我分享的那样立即调用函数表达式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 2019-06-20
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    相关资源
    最近更新 更多