How to deal with returns in async JavaScript when callbacks are not an option?

80 Views Asked by At

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?

1

There are 1 best solutions below

2
On BEST ANSWER

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
  // }
});