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.

1
  • $.getJSON returns jqXHR object which implements the Promise interface. So you could just return result of $.getJSON call. Commented Oct 6, 2014 at 13:45

1 Answer 1

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 …;
});
Sign up to request clarification or add additional context in comments.

5 Comments

You might also be interested in these general rules for working with promises.
It might be beneficial to give OP example usage of how the target function can be used from the outside by chaining then to it.
@BenjaminGruenbaum: [X] Done
Well, I can't upvote twice :P I think it really helps to tell people how usage works though.
Excellent! Thank you for doing this. I wish I could upvote this 10 times.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.