首页 > 请教大家普通jQuery回调代码如何改写成promise形式的?

请教大家普通jQuery回调代码如何改写成promise形式的?

javascriptfunction submitForm(){
    $('form').ajaxSubmit({
        success : function( json ){
            getData();        //调用另一个要请求数据的方法
            console.log('form submit success');
        },
        error : function( json ){
            console.log('form submit error');
        }
    });
}

function getData(){
    $.getJSON('xxx.php', function( json ){
        if( json.error ){
            console.log('get data error');
        }else{
            console.log('get data success');
        }
    });
}

点击按钮会有两个ajax操作,一个是用ajax提交数据,一个是去请求数据,两个请求之间无关联。之前一直都是不停的回调,然后自己看了promise,不是很懂啊。下面是改写后的版本,有几个问题想请教大家:

javasscriptvar myAjax = function(){
    var dtd = new $.Deferred();
    $.when( submitForm(), getData() )
        .then(function(){
            console.log('finish');
        });
};
  1. 请问$.when的时候,我是不是要分别在 ajaxSubmit 和 getJSON 的 success 和 error(共四个地方)写dtd.notify();
  2. dtd.resolve();什么时候用?
  3. ajaxSubmit 和 getJSON 后台返回的json数据我该怎么获取

技术渣,问题比较多啊,还请不要嫌弃
顺便求一个简单易懂jquery promise的文档QAQ


JQ的ajax方法返回的jqXHR对象默认带promise的功能,直接return出去就是promise化了

//手机码字,有空再细化

【热门文章】
【热门文章】