0

I'm trying to understand $.when(...).then(...).done(...). This is just tests.

Html:

<p id="phrase"></p>
<button id="btn">get phrase</button>

javascript:

var p = $('#phrase');

function displayResult(o){
    console.log(o);
    p.append(o + ' ');
};

function getSubject(){
    console.log('getSubject');
    return $.get(
    'sujet.js', //returns "the quick brown fox"
    displayResult
    );
}

function getVerb(){
    console.log('getVerb');
    return $.get(
    'verbe.js',//returns "jumps over"
    displayResult
    );  
}

function getComplement(){
    console.log('getComplement');
    return $.get(
    'complement.js', //returns "the lazy dog"
    displayResult
    );
}

function close(){
    p.append("!!!");
}

function load(){
    $.when(getSubject())
    .then(getVerb)
    .then(getComplement)
    .done(close);
}

$('#btn').click(load);

As I understand it, it should:

  1. request for sujet.js, display the string in the paragraph.
  2. request for verbe.js, display the string in the paragraph.
  3. request for complement.js, display the string in the paragraph.
  4. append "!!!" to the paragraph.

All it does is getting sujet.js. displayResult is never called, neither the functions passed to then and done.

So, I probably misunderstood something.

I got the example from this answer.

EDIT

My problem was a parse error, not related to $.when or $.then. Once fixed, the rest worked as expected. However I marked meagar's answer as accepted because it explained well how the thing works.

4

3 回答 3

2

$.when(...).then(...).done(...)不是一件事,从某种意义上说,你不需要 when,你不需要then,你不需要用 . 终止链done。只需将您的承诺返回函数与 链接在一起then,然后添加一个fail处理程序:

getSubject()
.then(getVerb)
.then(getComplement)
.then(close)
.fail(function () {
  console.log("One of the functions failed");
});

请注意,通过省略 afail您基本上错过了使用延迟而不是成功/失败回调的全部好处:使用一种统一的错误处理方法从任何级别“捕获”失败。

于 2013-08-09T20:38:20.487 回答
1

仅当前一个函数调用返回的/对象获得-d 或-ed.then()时,才会调用该部分。如果以错误终止,如果永远不会被解决或拒绝,则函数调用将永远等待。由于您所看到的,我假设函数中的 ajax 调用以异常方式终止。要查看是否是这种情况,只需在函数链中添加一个处理程序:$.Deferredpromistresolve()reject()$.get.then()$.getgetSubject().fail()

$.when(getSubject())
    .then(getVerb)
    .then(getComplement)
    .done(close)
    .fail() {
         console.log('An error occured.');
    });
于 2013-08-09T20:44:57.313 回答
0

您也可以通过这种方式进行调试。它将帮助判断其中一个功能失败的地方:

function getSubject(){
    console.log('getSubject');
    return $.get(
       'sujet.js', //returns "the quick brown fox"
       displayResult
    ).done(function() { console.log("subject failed"); });
}

其他类似。

于 2013-08-09T20:31:57.893 回答