JQuery deferred reject immediately

2020-04-02 09:11发布

When using JQuery.Deferred is it OK to invoke reject() directly? Without having invoked a async function?

Perhaps I want some kind of test in the beginning of my async function. If the test fails I want to reject immediately. See the first if block below.

function doSomethingAsync() {

    //Test if the ajax call should be invoked
    var testFailed = true;

    var dfd = $.Deferred();

    //Check if test failed
    if (testFailed) {
        var asyncResult = {
            success: false,
            data: 'test failed'
        };

        //Is this OK usage of reject on the same thread?
        dfd.reject(asyncResult);

        return dfd.promise();
    }


    $.get('/api/testapi/get').done(function (data) {
        var asyncResult = {
            success: true,
            data: data
        };

        dfd.resolve(asyncResult);
    }).fail(function (err) {
        var asyncResult = {
            success: false,
            data: err
        };

        dfd.reject(asyncResult);
    });

    return dfd.promise();
}

2条回答
兄弟一词,经得起流年.
2楼-- · 2020-04-02 09:26

When using JQuery.Deferred is it OK to invoke reject() directly? Without having invoked a async function?

Yes, it's totally OK to return an already rejected promise, and to reject deferreds immediately. You only might need to verify that your callbacks don't rely on asynchronous resolution, which jQuery does not guarantee (in contrast to A+ implementations).

Notice that in your code you should use then instead of manually resolving the deferred:

function doSomethingAsync() {

    var testFailed = /* Test if the ajax call should be invoked */;

    var dfd = testFailed 
          ? $.Deferred().reject('test failed')
          : $.get('/api/testapi/get');

    return dfd.then(function (data) {
        return {
            success: true,
            data: data
        };
    }, function (err) {
        return {
            success: false,
            data: err
        };
    });
}
查看更多
Fickle 薄情
3楼-- · 2020-04-02 09:46

You can do it quickly, as your function return a Promise object:

return Promise.reject('test failed');
查看更多
登录 后发表回答