0

If i have this code:

app.get("/location1", function(req, res){
   async_function().then(result => {
       var str = result.toString();
   }).catch(...).....
});

There are variables inside the .then() of the asynchrouns function.

(result, str)

Can i use these variables in another route then?

app.get("/location2", function(req, res){
   result = ....;
   str = ...;
});

Aren't the variables scope, limited to only inside the .then() function?

user1584421
  • 3,499
  • 11
  • 46
  • 86
  • Whats your usecase? and yes, you can. – Jonas Wilms Sep 14 '18 at 15:06
  • Thanks! What do you mean usecase? – user1584421 Sep 14 '18 at 15:07
  • Aren't the variables scope, limited to only inside the .then() function? – user1584421 Sep 14 '18 at 15:08
  • what is this code supposed to do? whats the "big picture"? – Jonas Wilms Sep 14 '18 at 15:11
  • It runs an asynchrouns function. The result of the asynchronous function (an array) will be given back to the user in the form of a text file – user1584421 Sep 14 '18 at 15:16
  • So can i use these variables declared inside the .then() to another route? – user1584421 Sep 14 '18 at 15:17
  • I know what the code does, I want to know what you want to achieve with that? what is inside the array and why is that needed in two routes? – Jonas Wilms Sep 14 '18 at 15:20
  • Inside the array are data that i want the user to download. I used to do it in one route. After a post, the function calculates the result and gives it to the user in the form of a text file with setting headers. I uploaded to Heroku, but because this function takes time, it triggered a timeoute error. I cannot do a res.render() then a res.send() the headers. So i try another way by doing a res.render() and when the function has ended, send an event to client with socket.io. The rendered page then will unlock a div with a link, that when the client follows it, opens a new tab, serves the txt. – user1584421 Sep 14 '18 at 15:24
  • So can i use these variables declared inside the .then() to another route? – user1584421 7 mins ago – user1584421 Sep 14 '18 at 15:25
  • Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – ponury-kostek Sep 14 '18 at 15:36
  • @user154421 that seems to be your actual question. Could you please [edit] that in? – Jonas Wilms Sep 14 '18 at 15:46
  • @JonasWilms I have already posted this question with no real answer... Now, i finally found a solution in socket.io. So what i am asking here is very specific, there is no need to add all the extra information. – user1584421 Sep 14 '18 at 16:00

2 Answers2

0

It massively depends on the context of your code. If you simply want to assign data to a user that can be used when they visit /location2 you can store the variable as a cookie. Then using the cookie-parser middleware you can easily read the data from the request.

app.get("/location1", function(req, res) {
    async_function().then(result => {
       var str = result.toString();
       res.cookie("str", str);    //store the str variable as a cookie with the name "str"
       res.send(200, 'ok')
    }).catch(...).....
});

app.get("/location2", function(req, res) {
    var str = req.cookies.str;    //save the value of the "str" cookie as a varable
});
0

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.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151