JQuery deferred reject immediately

前端 未结 2 1381
情深已故
情深已故 2021-01-17 23:10

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 asy

2条回答
  •  天涯浪人
    2021-01-17 23:51

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

提交回复
热议问题