2

Let's say I have some JS that makes an AJAX call like this:

$.getJSON(myUrl, { targetState: state }, function (jsonData) {
}).success(function (jsonData) {
    ...
    ...
    ...
});

Now let's assume I want to wrap this code in a function and have it return some value, in the success block, so I can call it from various places in my app. Should the function I create return a Promise? I'm thinking it probably does, but I've never created a JS function that returned a Promise so I'm not entirely certain when I need to do this.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Randy Minder
  • 47,200
  • 49
  • 204
  • 358
  • `$.getJSON` returns `jqXHR` object which implements the Promise interface. So you could just return result of `$.getJSON` call. – hindmost Oct 06 '14 at 13:45

1 Answers1

4

Should the function I create return a Promise

Yes. If you want to use promises, every function that does anything asynchronous should return a promise for its result. No exceptions, really.

wrap this code in a function and have it return some value in the success block

Good news: It's not complicated, as $.getJSON does already give you a promise to work with. Now all you need to do is to use the then method - you can pass a callback to do something with the result and get back a new promise for the return value of the callback. You'd just replace your success with then, and add some returns:

function target(state) {
    var myUrl = …;
    return $.getJSON(myUrl, { targetState: state })
//  ^^^^^^
    .then(function (jsonData) {
//   ^^^^
        /* Do something with jsonData */
        return …;
//      ^^^^^^
    });
}

With promises, you do no more pass a callback to the $.getJSON function any more.

so I can call it from various places in my app

Now, you can call that target function, and get the result of the returned promise in another callback:

target({…}).then(function(result) {
    …; return …;
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375