【发布时间】: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