Reputation: 131
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
?
Upvotes: 0
Views: 107
Reputation: 364
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;
}
Upvotes: 1
Reputation: 7770
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);
})();
Upvotes: 1