Search code examples
javascriptajaxecmascript-6es6-promiseaxios

if/else block with a return and an ajax promise


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.


Solution

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