简体   繁体   中英

Exports NODEJS getting response as ''undefined''

I use the following code:

MYCODE.JS FILE:


function getName() {
  (async ()=>{
  let bodyapi = await axios.get(`www.API-EXAMPLE.com`)
  console.log("You've requested a number with the following ID: " + bodyapi.data.slice(14, 22));
  console.log("You've requested a number with the following NUMBER: " + bodyapi.data.slice(-11));
  const number = bodyapi.data.slice(-11);
  return number;
  })();
}
exports.getName = getName;

Then after exporting it I try using it.

MYAPP.JS FILE

const number = require('./requestnumber.js');


setTimeout(() => {
    console.log(number.getName());
}, 5000);

Console results:

undefined
You've requested a number with the following ID: MYID
You've requested a number with the following NUMBER: MYNUMBER

I want ''undefined'' to show as my number. When I console.log it on MYCODE.JS under the async, it shows the number I want, but when I try it out of the async or after exporting it, it shows as undefined.

Also, yes, I tried using number.getname() before console.log (g-ing) it, but I just can't manage to get it right. I tried 4 different ways, and I keep getting undefined. I don't know what to do, because the api takes around 1-2 seconds to get the number and ID, and it only works under the async on MYCODE.js file . Any ideas how I can do that without getting the exported number on my other file as undefined ?

Mycode.js

async function getName() {
  let bodyapi = await axios.get(`www.API-EXAMPLE.com`)
  console.log("You've requested a number with the following ID: " + bodyapi.data.slice(14, 22));
  console.log("You've requested a number with the following NUMBER: " + bodyapi.data.slice(-11));
  const number = bodyapi.data.slice(-11);
  return number;
}

module.exports = getName;

MYAPP.JS FILE

const getName = require('./requestnumber.js');

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

You have a anonymous function inside getName function That function is async. so getName func returns undefined before inner function returns. then inner function works. and print out console. so if you write

function getName() {
  let bodyapi = await axios.get(`www.API-EXAMPLE.com`)
  console.log("You've requested a number with the following ID: " + bodyapi.data.slice(14, 22));
  console.log("You've requested a number with the following NUMBER: " + bodyapi.data.slice(-11));
  const number = bodyapi.data.slice(-11);
  return 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