-1

Of course, there are many async questions and answers. But my question is about an async situation in which I need to return something.

I have this in node express:

app.use('/', FalcorServer.dataSourceRoute(function(req, res) {
         return new someClass('SOMEHOST', req.query.paths);
}));

Now my problem is this, someClass is async because of AJAX. (in my example I use setTimeout to make my point).

Something like this:

class someClass {
    constructor(redisHost, pathString) {
        return setTimeout(function(){
            return someModel;
        }, 1500);
    }
}

module.
    exports = someClass;

But I have to deal with this return in my app.use, how can I do this?

Bob van Luijt
  • 7,153
  • 12
  • 58
  • 101
  • 3
    Bang your head against the wall, because without callbacks, asynchronous code isn't going to work very well (read as "at all"). – Kevin B Oct 08 '15 at 15:05
  • 2
    I'm guessing you've seen [this question](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call). The answer is still the same really - you're still going to have to adjust your code to use a callback. Perhaps your constructor returns a function that takes a callback as an argument, and it's that function that calls `setTimeout`. – James Thorpe Oct 08 '15 at 15:06
  • Ok thanks, any hints or directions where I could find a solution to this? – Bob van Luijt Oct 08 '15 at 15:09
  • 2
    You could restructure this a bit. You could make the AJAX call *first* and then in the callback, call `app.use`. – gen_Eric Oct 08 '15 at 15:10

1 Answers1

1

I think you need to adjust your thinking ... app.use goes inside the callback. Without fully understanding all the full details of your issue I think this might help you.

function someClass(a, b, callback) {
  return setTimeout(function(){
    callback(a+b);
  }, 1500);
}

new someClass(1, 2, function(response) {
  console.log(response === 3);
  // your app.use statement which needs the response goes here.
  // In fact all your express (im guessing you are using express) stuff goes here
  // Example
  // app.use('/', FalcorServer.dataSourceRoute(function(req, res) {
  //    return response
  // }
});
danday74
  • 52,471
  • 49
  • 232
  • 283