Of course it won't, it's an asynchronous function. The simplest solution is to do move that callback from getData
to invoke
, so that invoke can pass it into getData, and getData can then called "whatever you need to have continue happening" once data is available:
var Thing = {
....
invoke: (andThenDoThis) => {
Thing.getData(andThenDoThis);
},
getData: (andThenDoThis) => {
request(options, function(err, res, body) {
if (res && (res.statusCode === 200 || res.statusCode === 201)) {
logger.info("vacation balacne response:" + body);
}
// THIS IS WHERE YOUR CODE WILL NOW CONTINUE:
if (andThenDoThis) {
andThenDoThis(err, res, body)
}
});
},
...
};
Although of course this is silly because just define an object with this
referencing instead:
class Thing {
constructor(options) {
this.options = options;
}
invoke() {
this.getData((err, res, body) => {
this.handleData(err, res, body);
});
}
getData(andThenDoThis) {
request(this.options, (err, res, body) => {
this.handleData(err, res, body)
});
}
handleData(err, res, body) {
// do some `err` checking
// do some `res` checking
// do some `body` parsing
// do whatever else
if (this.options.forwardData) {
this.options.forwardData(...);
}
}
...
}
And then just make one of those things:
// make a thing:
let thing = new Thing({
...,
forwardData: (data) => {
// do whatever with your data.
},
...
});
// and then invoke whatever it is you actually needed to do.
thing.invoke();
// code here keeps running, but that's fine, because now you're
// using "code triggers only when, and where, it needs to".