You cannot do this with asynchronous code, let alone synchronous code. You will never have access to the variable trans
outside of the scope of the function it is defined in.
If you want to have access to the value that trans
represents outside of the function trans
is defined in, you need some kind of events or streaming.
Try RxJS.
With RxJS you can do the following (not tested):
var trans = Rx.Subject();
var startDate = moment().subtract(30, 'days').format('YYYY-MM-DD');
var endDate = moment().format('YYYY-MM-DD');
plaidClient.getTransactions(AccessToken, startDate, endDate, {
count: 250,
offset: 0,
}, function(error, transactionsResponse) {
if (error != null) {
console.log(JSON.stringify(error));
return response.json({
error: error
});
}
// Pass the value into the stream.
trans.next(transactionsResponse);
});
// Every time the `trans.next(...)` line is called in the HTTP call,
// this function will be invoked.
trans.asObservable().subscribe(function (transactionsResponse) {
// use "transactionsResponse" how you please...
});
What we do above is create a subject, called trans
. When your HTTP response comes back, we add the value to the trans
subject stream. And at the bottom, we subscribe to that stream, and any time something is added to it the callback will be invoked. This way you always have the "access" you are looking for to trans, even with asynchronous code.