问题
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:
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 …;
});
来源:https://stackoverflow.com/questions/26217478/does-this-javascript-function-need-to-return-a-promise