【发布时间】:2020-12-23 18:53:53
【问题描述】:
我正在编写一个包含许多调用 API 的函数的 Discord 机器人,因此我在我的项目中添加了一个 functions.js 文件,其中包含我似乎经常使用的不同函数,例如从 API 调用中获取数据。
在我的functions.js 文件中,我有这样的代码:
const axios = require('axios');
function randomEl(arr) {
const index = Math.floor(Math.random() * arr.length);
return arr[index];
}
function axiosGet(url) {
axios.get(url).then((response) => {
const { data } = response;
return data;
}).catch((err) => {
throw err;
});
}
module.exports = {
randomEl,
axiosGet
}
我在 return 语句之前放了一个 console.log,它显示了 axios 数据,但是当我记录函数在我的 index.js 文件中返回的值时,它是 undefined。
我的index.js 文件如下所示:
const fns = require('./functions.js');
try {
const url = `https://api.tenor.com/v1/search?q=${searchTerm}&key=${process.env.TENNOR_KEY}`;
const data = fns.axiosGet(url);
console.log(data);
} catch (err) {
console.log(err);
msg.reply('An Error Has Occured');
}
这部分代码中的数据是undefined,但在返回之前的实际axiosGet函数中,当我记录它时,它会显示正确的数据。
【问题讨论】:
标签: javascript function axios return node-modules