Aren't the variables scope, limited to only inside the .then() function?
Yes the arguments of a function can only be accessed inside of the function itself. However you could assign that argument to a global variable, and that can be accessed inside other functions:
let result; // global variable
app.get("/location1", function(req, res){
async_function().then(res => {
result = res.toString(); // assign to global
}).catch(/*...*/);
});
Now that global variable is shared between all instances. That means if one user requests location1, the result gets assigned to redult and another user that requests location2 will get that. To resolve that, you have to store the result related to some user token, and the user can then pass the token to get his result:
const results = {};
// Loads the data into the results object
async function loadData(token) {
const result = await async_function();
results[token] = result;
}
app.get("load", (req, res) => {
// Generate unique token:
require('crypto').randomBytes(48, function(err, buffer) {
var token = buffer.toString('hex');
// Load data (fire & forget)
loadData(token);
// And respond with the token:
res.json({ token });
});
});
app.get("result/:token", (req, res) => {
const { token } = req.params;
if(results[token) {
res.send( results[token] );
} else {
res.status(404).end("Not found :(");
}
});
Then you can request /load
and get back a token, such as 1234
then you can poll result/1234
and wait for the result to appear.