[英]My module.exports return as [object Object]
我使用 API 来获取我需要的一些信息。
let bodyapi = await axios.get(`www.example.com`)
然后我像这样导出我需要的信息:
const number = bodyapi.data.slice(-11);
module.exports = number
然后我用const number = require('./myapp.js')
在我的实际文件上运行它(像往常一样)。
但问题是,当我读取它时,它返回[object Object]
const number = require('./myapp.js')
sleep(5000) // It's a timeout function I've set, ignore it, it's just so I don't run the code too fast since it uses API''
console.log("Your ID: " + number) //Here is where it reads as [object Object]
控制台结果:
Your ID: [object Object]
我的问题是:我该如何修复它,以便它读取我需要读取的内容? bodyapi 被制成一个“异步”函数。 我使用Axios
来读取 api。
如果您需要更多信息,请在评论中告诉我,以便我可以编辑这篇文章。 谢谢你的时间!
我认为这不是从异步函数导出响应并将它们与睡眠一起使用的正确方法。 您应该考虑像这样导出函数
async function getResponse() {
let bodyapi = await axios.get(`www.example.com`);
const number = bodyapi.data.slice(-11);
return number;
}
module.exports = getResponse;
那么无论你想用在哪里,你都可以像这样使用它
const getResponse = require('./myapp.js');
getResponse()
.then(number => console.log(number));
或使用异步/等待
const getResponse = require('./myapp.js');
(async() => {
const number = await getResponse();
console.log(number);
})();
将其记录为 [object object]。 如果您尝试将对象与字符串连接起来,您将看到该行为。
问题出在控制台日志上。 您正在对数字对象进行字符串化:尝试以下操作:
const number = require('./myapp.js')
sleep(5000) // It's a timeout function I've set, ignore it, it's just so I don't run the code too fast since it uses API''
console.log("Your ID: ", number) //
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.