[英]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.