Does this JavaScript function need to return a Promise?

好久不见. 提交于 2019-12-12 10:05:35

问题


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


来源:https://stackoverflow.com/questions/26217478/does-this-javascript-function-need-to-return-a-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!