0

I'm new to JavaScript, I need to refactor some code that looks like this:

    [initial code - resolves condition]
    if(condition) {
      $.get("[api1]", function(result) {
          doStuffWith(result);
       });
    }
    else {
      $.get("[api2]", function(result) {
          doStuffWith(result); // <-- same stuff as before
       });
    }

I want to refactor it to something like the following:

 function getResult() {
       [initial code - resolves condition]
       if(condition) {
          $.get("[api1]", function(result) {
              res = result;
          });
        }
        else {
          $.get("[api2]", function(result) {
            res = result;
          });
       } 
       return res;
     }

...

var result = getResult();
doStuffWith(result);

I need this partly for readability but mostly because I need to reause the getResult() functionality in another place.

Problem is, the ajax calls - $.get() are asynchronous. The function they take will execute at some point in the future when the ajax call returns.

How do I turn this into a reusable bit of code? How do I then use it?

Shaggydog
  • 3,456
  • 7
  • 33
  • 50
  • [Using Promises | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) – Andreas Feb 26 '20 at 17:51
  • Async logic cannot work in the manner you want to change it. This is why it's done as it is originally, ie. the common logic is extracted in to a function which is invoked in the callback of both requests – Rory McCrossan Feb 26 '20 at 17:52

0 Answers0