【问题标题】:Node JS: Can't Return Data and Export from Async Axios FunctionNode JS:无法从异步 Axios 函数返回数据和导出
【发布时间】:2020-06-25 14:07:05
【问题描述】:

这是一个非常简单的示例,取自 Axios 文档和各种博客文章:

我要做的就是从异步函数返回数据并在其他地方调用它:

在文件中:axios.js

const axios = require("axios");

async function getJson() {
  const url = "https://jsonplaceholder.typicode.com/posts/1";  
  const response = await axios.get(url);
  const data = response.data;
  return data;
}

console.log(getJson());

然后我运行node axios.js

但是,它没有按预期从 api 中注销实际的 Json 数据,而是使用以下命令记录 Promise: Promise { <pending> }

这个非常简单的例子取自这篇文章:https://scotch.io/tutorials/asynchronous-javascript-using-async-await (在错误处理部分上方)。

我在这里误解了一些基本的东西吗?抱歉,这令人非常沮丧,我已经阅读了几篇博客文章和堆栈溢出文章,但没有任何解释或提供答案。

目前我正在处理这个文件,但后来的想法只是在另一个文件中导入并调用此函数并获取该函数返回的数据。

【问题讨论】:

    标签: javascript node.js async-await axios


    【解决方案1】:

    您的函数是async,这意味着它返回一个Promise,正如您已经发现但显然没有预料到的那样。

    你需要await函数调用。例如

    console.log(await getJson());
    

    或者,你也可以这样做:

    getJson().then(json => {
        console.log(json);
    });
    

    简单示例:

    
    const getAppointment = (appointmentId) => {
        return axios.get("example.com");
    };
    
    getAppointment(123).then(response => {
    
        if (response.status === 200) {
            console.log(response.data); // Do what you want with the JSON
        }
    
    });
    
    

    【讨论】:

    • 你不能这样做:console.log(await getJson()); - 它说:SyntaxError: missing ) after argument list
    • 关于 then 示例 - 我认为 async/await 的重点是编写看起来同步的代码并远离 then 语法。
    • @daneasterman 我建议您离开并正确理解该主题,或者尝试观看youtube.com/watch?v=QO4NXhWo_NM。他非常擅长解释基础知识。一旦你认为你理解了,然后编写代码。
    • 还有:getJson().then(json => { console.log(json); });打印出所有内容,而不仅仅是数据。 json.data 也无济于事。
    • @rhy_stubbs 在为我的真实示例编写代码之前,我一直在阅读和研究 Promise 以尝试理解它。这也是为什么我回到这个简单的例子,试图回到第一原则。
    【解决方案2】:

    你需要等待异步请求,例如,

    import { getJson } from '../file';
    async function printJSON() {
      const jsonData = await getJson();
      console.log(jsonData);
    }
    

    因为这里的 getJSON 是一个异步函数。

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 2020-04-22
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 2017-08-24
      • 2018-05-15
      • 2016-08-11
      • 2015-04-21
      相关资源
      最近更新 更多