Question

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();
}
Était-ce utile?

La solution

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

Autres conseils

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

return Promise.reject('test failed');
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top