【问题标题】:Data undefined in Async data return异步数据返回中未定义的数据
【发布时间】:2021-08-01 21:46:31
【问题描述】:

我遇到了来自位于控制器文件中的异步函数的返回数据的问题。
我想在“let data”中获取我的数据,但它是未定义的,我不明白我的错误在哪里..
(当然在我的异步函数概念中:))

这是我的例子:

// index.js
const DataController = require('../controllers/DataController');

router.get('/test', function (req, res, next) {

  let data = DataController.getData().then((resp) => {
    console.log(resp); // <-------- here is undefined

  });
});

// DataController.js
const axios = require('axios').default;
exports.getData = async function getData() {
        return axios.get("https://it.lipsum.com/")
            .then((response) => {
                // console.log(response)
                return response;
            })
            .catch(function (error) {
                // handle error
                console.log(error);
            })
            .then(function () {
                // always executed
            });
    }

【问题讨论】:

  • .then(function () { // always executed });这里的代码是什么?
  • 不要混合使用 promises 和 async/await,使用其中一个
  • 这应该是:const response = await axios.get("https://it.lipsum.com/");
  • @RogerAI 好吧,这就是问题所在。如果你有promise.then().then(),那么second .then() 会从前一个.then() 的返回值中获取它的值。所以,如果你有一个.then(),在你之前没有返回任何东西,你会得到undefined

标签: javascript node.js async-await promise axios


【解决方案1】:

您需要从then 调用中返回数据。

// DataController.js
const axios = require('axios').default;
exports.getData = async function getData() {
        return axios.get("https://it.lipsum.com/")
            .then((response) => {
                // console.log(response)
                return response;
            })
            .catch(function (error) {
                // handle error
                console.log(error);
            })
            .then(function (res) {
                // always executed
                return res;
            });
    }

Promise 始终返回最后一个值 .then 调用返回的工作方式,因此您的最后一个 .then 调用返回然后 undefined

关于let data = 的小注释,因为调用是async,您将看到Promise 而不是promise 将解析的数据。您可以通过以下方式使用async/await 语法。

router.get('/test', async function (req, res, next) {

  let data = await  DataController.getData();
});

【讨论】:

  • 两次返回相同的结果是没有意义的
  • 我已经尝试过此解决方案,但无法正常工作。我用过@Liam const resp = axios.get();并在第一页 .then( (resp) => console.log(resp) );那工作就像一个魅力
  • 是的,没有意义。我只是描述了当前代码的问题,以及为什么这不起作用。
【解决方案2】:

像这样重构你的文件:

index.js

// index.js
const { getData } = require('../controllers/DataController');

router.get('/test', async (req, res, next) => {
  try {
    let data = await getData();
    console.log(data);
    return res.status(200).json(data);
  } catch (error) {
    console.log('ERROR: ', error);
    return res.status(400).json({
      success: false,
      error
    });
  }
});

DataController.js

const axios = require('axios').default;

const getData = async () => {
  try {
    let response = await axios({
      method: 'get',
      url: "https://it.lipsum.com/"
    });
    return response
  } catch (error) {
    return error;
  }
}

module.exports = { getData };

【讨论】:

    猜你喜欢
    • 2019-10-03
    • 2021-10-03
    • 1970-01-01
    • 2016-05-07
    • 2023-04-03
    • 2018-09-22
    • 1970-01-01
    相关资源
    最近更新 更多