首页 > 解决方案 > 延迟对象 catch() 方法链接

问题描述

我是 jQuery 的新手。我目前正在学习 jQuery 中的延迟对象。我在运行我的 jQuery 代码时遇到问题。

问题是当我的延迟对象以已解决状态返回时,它正在调用被调用successCallBack的函数,done()但在该函数之后定义的函数catch()也被执行。

为什么会这样?

感谢您的任何建议。

$(document).ready(function () {

    $('#btnLoadImage').click(function () {

        var dfd = getImages(); // Returns Deferred object

        dfd.always(alwaysCallBack('Ajax is Called'));

        dfd.progress(progressCallback);

        dfd.done(successCallBack);

        dfd.catch(errorCallback).then(function () {
            console.log(dfd.state());
            setTimeout(function () {
                $('.gallery').empty();
                $('.gallery').append('<center><input type="button" id="btnTryAgain" style="width:200px" class="btn btn-primary" value="Try Again" /></center>');
            }, 3000);
        });
        
    });

    $('.gallery').on('click', '#btnTryAgain', function () {

        console.log('Hello');
        $('.gallery').empty();
        $('#btnLoadImage').click();

    })  

    function getImages() {

        var dfd = new $.Deferred();

        $.ajax({
            method: 'GET',
            url: 'https://api.pexels.com/v1/search?query=car',
            dataType : 'json',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', API_KEY);
                xhr.setRequestHeader('Accept','application/json');
            },
            success: function (data) {
                dfd.notify('Loading...');
               setTimeout(function () { dfd.resolve(data) }, 3000);

            },
            error: function (error) {
                dfd.notify('Loading...');
                setTimeout(function () { dfd.reject('Response Rejected.') }, 3000);
                
            }
        });

        return dfd.promise();
    }

    function successCallBack(data) {

        $('.gallery').empty();

        data.photos.forEach(photo => {
            const item = document.createElement('div');
            item.classList.add('item');
            item.innerHTML = `<img src="${photo.src.medium}">`;
            $('.gallery').append(item);
        });
    }

    function errorCallback(errorMessage) {
        $('.gallery').empty();
        $('.gallery').append('<p><h1 style="color:red">' + errorMessage + '</h1></p>');
    }

    function progressCallback(progressMessage) {

        $('.gallery').empty();
        $('.gallery').append('<p><h1>' + progressMessage + '</h1></p>');
    }

    function alwaysCallBack(message) {
        console.log(message);
    }      
}); 

延期解决:

在此处输入图像描述

调用后定义的函数catch()

在此处输入图像描述

标签: jqueryes6-promise

解决方案


推荐阅读