I have this express POST route.Which i'm hitting with the help of jQuery using axios.
app.post("/user", jsonParser, (req, res) => {
const requrl = req.body.url;
const URL = extractprofile(requrl);
const shorturl = URL.shorturl;
const longurl = URL.longurl;
const regex = /^[0-9]*$/i;
const matches = regex.exec(shorturl);
if (matches === null) {
getSteamID64(longurl)
.then(function (result) {
const steam64 = result;
**const data = playerInfo(steam64)**;
console.log(data) // undefined
})
.catch(function (error) {
console.log(error);
})
} else {
const steam64 = shorturl
**const data = playerInfo(steam64)**;
console.log(data); //undefined
}
})
Lets just focus on const data = playerInfo(steam64).The code for the function playerInfo(steam64) is below:
function playerInfo(steam64) {
SteamApi.getPlayerInfo(steam64, "D295314B96B79961B1AB2A2457BA5B10", (err, data) => {
if (err) {
console.log("error", err);
} else {
console.log(data);
return data
}
})
}
This function does a API call to steam and gets the playerinfo.Whose profile link we are passing as a parameter to the function. I guess the problem is asynchronosity of javascript. Before the function returns the value. console.log(data) // In the post route is executed so it is console logging undefined.
I tried this :
async function playerInfo(steam64) {
let response
try {
response = await SteamApi.getPlayerInfo(steam64, "D295314B96B79961B1AB2A2457BA5B10",(err, data) => {
if (err) {
console.log("error", err);
} else {
console.log(data);
});
}
catch (error) {
console.log(error);
}
return response;
}
//POST ROUTE
playerInfo(steam64).then(steamdata => {
console.log(steamdata); //undefined
});
The above async function refractor also doesnt work.VSCODE keeps telling me 'await has no effect in this type of expression'.And surely even after this it console logs 'undefined'.
It works when i replace the 'playerInfo(steam64)' function call with the entire function.But the POST route will become too much clumsy.I want to divide the code into functions. Any help is appreciated.The goal is to run playerInfo(steam64) in the post route.And make the playerInfo(steam64) function to return the result.