簡體   English   中英

JQuery立即推遲拒絕

[英]JQuery deferred reject immediately

使用JQuery.Deferred時可以直接調用reject()嗎? 沒有調用異步函數?

也許我想在異步函數的開頭進行某種測試。 如果測試失敗,我想立即拒絕。 請參閱下面的第一個if塊。

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

使用JQuery.Deferred時可以直接調用reject()嗎? 沒有調用異步函數?

是的,完全可以返回已被拒絕的承諾,並立即拒絕延期。 您可能只需要驗證您的回調不依賴於異步解析,jQuery不保證(與A +實現相反)。

請注意,在您的代碼中,您應該使用then而不是手動解析延遲:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM