You can't, with your current setup. This is the way it's meant to be. Whatever you do with those variables can't leave that function.
You can pass the data somewhere else though using a function like this:
const { hiscores } = require('runescape-api');
var rsn = "le me";
function doSomethingWithData(rsname, rslevel, rsexp) {
console.log(rsname, rslevel, rsexp);
}
var rsnlookup = hiscores.getPlayer(rsn).then(data => {
var rsname = data.name;
var rslevel = data.skills.dungeoneering.level;
var rsexp = data.skills.dungeoneering.experience;
doSomethingWithData(rsname, rslevel, rsexp);
})
rsnlookup.catch((error) => {
console.error("This username doesn\'t exist.");
});
This is how JavaScript is supposed to work. Whenever you make a call out to another server, JS does not stop and wait for the request to come back. It actually continues executing onward while the request is still traveling across the internet to you. This is why you need to provide a callback function for it to come back and execute when it's done.
So for example, here's a simpler breakdown:
// The variables must be declared outside the function for them
// to be accessible from outside the function.
let rsname;
let rslevel;
let resexp;
// This call only BEGINS the request. It will not stay and wait for it.
hiscores.getPlayer(rsn).then(data => {
// This code is only executed after the request comes back with the data,
// so the data can only be used from here.
// These variables do not get declared until this time,
// so they won't exist outside this function until the request is done.
// You need to pass them out to wherever they are needed from here,
// or do all your logic with it right here.
rsname = data.name;
rslevel = data.skills.dungeoneering.level;
rsexp = data.skills.dungeoneering.experience;
});
// This is executed the moment the request begins, it does not wait for it to return.
console.log(rsname); // The variables are still undefined here since the request is not back yet here.
Essentially, all "asynchronous" means is that the code will BEGIN executing, and continue onward without waiting for it to finish. Then when it's done it comes back to execute some kind of callback function.