简体   繁体   中英

My module.exports return as [object Object]

I use an API to get some information I need.

let bodyapi = await axios.get(`www.example.com`)

Then I export the information I need like this:

const number = bodyapi.data.slice(-11);

module.exports = number

And then I run it on my actual file with const number = require('./myapp.js') (like always).
But the problem is that when I read it, it returns [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]

Console Result:

Your ID: [object Object]


My question is: How can I fix it, so it reads what I need it to read? The bodyapi is made into an ''async'' function. I use Axios to read the api.


If you need more info let me know in the comments so I can edit this post. Thanks for your time!

I don't think that is correct way of exporting response from async function and using them with sleep. You should consider exporting the function like this

async function getResponse() {

  let bodyapi = await axios.get(`www.example.com`);
  const number = bodyapi.data.slice(-11);
  return number;
}

module.exports = getResponse;

Then wherver you want to use it, you can use it like this

const getResponse = require('./myapp.js');

getResponse()
  .then(number => console.log(number));

OR using async/await


const getResponse = require('./myapp.js');

(async() => {
   const number = await getResponse();
   console.log(number);
})();

Regarding it logging as [object object]. If you try concatenate an object with string you will see that behaviour.

The problem is with the console log. You are stringifying your number object: Try the following:

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) //

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM