此JavaScript函数是否需要返回Promise? [英] Does this JavaScript function need to return a Promise?

查看:82
本文介绍了此JavaScript函数是否需要返回Promise?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一些JS可以像这样进行AJAX调用:

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

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

现在让我们假设我想将此代码包装在一个函数中,并使其在成功块中返回一些值,因此我可以在应用程序的各个位置调用它.我创建的函数应该返回Promise吗?我以为可能会这样做,但是我从未创建过一个返回Promise的JS函数,所以我不确定何时需要这样做.

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.

推荐答案

我创建的函数是否应返回Promise

Should the function I create return a Promise

是的.如果要使用Promise,每个函数可以执行异步操作,则应针对其结果返回一个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

好消息:这并不复杂,因为$.getJSON已经使您可以使用.现在,您所需要做的就是使用 then方法-您可以传递回调对结果做些事情,并为回调的返回值重新获得一个新的promise.您只需将success替换为then,然后添加一些return:

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

有了诺言,您就不再需要将回调传递给$.getJSON函数了.

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

现在,您可以调用该target函数,并在另一个回调中获取返回的promise的结果:

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

target({…}).then(function(result) {
    …; return …;
});

这篇关于此JavaScript函数是否需要返回Promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆