JQuery立即推迟拒绝 [英] JQuery deferred reject immediately

查看:100
本文介绍了JQuery立即推迟拒绝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JQuery.Deferred时可以直接调用reject()吗?没有调用异步函数?

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

也许我想在异步函数的开头进行某种测试。如果测试失败,我想立即拒绝。请参阅下面的第一个if块。

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


推荐答案


使用JQuery.Deferred时可以直接调用reject()吗?没有调用异步函数?

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

是的,返回已被拒绝的承诺并立即拒绝延迟是完全可以的。你可能只需要验证你的回调不依赖于异步解析,jQuery不能保证(与 A + implementation )。

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

这篇关于JQuery立即推迟拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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