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 return
s:
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 …;
});