0

I have an if/else block that looks like this:

if (this.getSessionStorageData()) {
    this.initialData(this.getSessionStorageData());
} else if (this.shouldPerformXHR) {
    this.loadXHRData();
}

Prefably I would like to expand this block, optionally create it into a switch statement perhaps a little something like this:

let data = [];

if (this.getSessionStorageData()) {
    data = this.getSessionStorageData();
} else if (this.shouldPerformXHR) {
    data = this.loadXHRData();
}

return data;

But the loadXHRData is an AJAX request. I am guessing in this example that if shouldPerformXHR is true that data will be returned before the AJAX request has finished.

Now the XHR request is actually a promise so I could catch the call and use a then but my sessionStorage data is not using a promise.

Is there any way I could kind of have the same data structure like my second example but with my promise or is this impossible?

I would like a method to simply return the data with whatever strategy is necessary(ajax, session, etc). But currently it looks like I am forced to set my data from the ajax requests's .then clause which leads to me having logic all over the place.

Hopefully this makes sense, if not please ask away.

Stephan-v
  • 19,255
  • 31
  • 115
  • 201
  • well you can not return from an call so you got to deal with promises, so have the getSessionStorageData return a promise and set it to resolve right away. – epascarello Sep 27 '17 at 12:35
  • You're looking for `Promise.resolve`. Yes, you are forced to always treat the function as asynchronous. – Bergi Sep 27 '17 at 13:34

1 Answers1

1

Resolving an asynchronous call synchronously will not work. So your data = this.loadXHRData(); will not be able to function this way.

This would mean that your function should return something to resolve by your callee because your AJAX call cannot be resolved in line here

So we could return a Promise instead which resolves for the value this.getSessionStorageData(); returns:

if (this.getSessionStorageData()) {
    return Promise.resolve(this.initialData(this.getSessionStorageData()));  // Will return a new Promise which is then-able.
} else if (this.shouldPerformXHR) {
    return this.loadXHRData();
}

And your callee should resolve this Promise by doing:

myFunction().then(function(data) {
 // do stuff with the data
});
Jeffrey Devloo
  • 1,406
  • 1
  • 11
  • 20
  • Ok so calling `.resolve` will immediately resolve it? This could be pretty neat although it feels weid to wrap everything else in Promises but I guess it makes sense. – Stephan-v Sep 27 '17 at 13:00
  • Well it's the only option you have. The AJAX cannot be resolved synchronously so your code will have to adapt to its async nature – Jeffrey Devloo Sep 27 '17 at 14:51