使用 jQuery 延迟链接异步函数

Using jQuery deferred to chain asynchronous functions

我正在尝试使用 jQuery $.Deferred 通过 then.

将函数链接在一起

我已经通读了文档并且很确定我在某个地方犯了一个愚蠢的错误,但是我无法让函数 second 等待 first 完成。

HTML

<ul>

</ul>

JS (jQuery 2.1)

function first () {
    let deferred = $.Deferred();
    setTimeout(function () {  // Any async function.
        $('ul').append('<li>First</li>');
        deferred.resolve();
    }, 500);
    return deferred.promise();
}

function second () {
    let deferred = $.Deferred();
    $('ul').append('<li>Second</li>');
    deferred.resolve();
    return deferred.promise();
}

$(function () {
    $.when(first()).done().then(second());
})

实际上,我想继续链接(因此也是 second 中的承诺)。

JSFiddle:https://jsfiddle.net/jdb1991/n3aory8c/

有什么想法吗?提前致谢。

删除 then() 回调中 second 函数的方括号 ()。否则,您将直接执行 second 函数,而不是在 promise 解析时执行。

$.when(first()).done().then(second);

Working example.

实际上,当您只有一个承诺时,使用 $.when() 根本没有意义。直接用.then()就可以了:

 first().then(second);

而且,对于 second,您必须传递一个函数引用,这意味着您只传递函数名称。如果你在它后面有 (),它会立即执行并传递 return 结果,而不是仅仅传递稍后可以由 .then() 基础设施调用的函数引用。

$.when() 只有当你有多个承诺并且你想知道所有承诺何时完成时才真正有用。当你只有一个承诺时,你可以直接在那个承诺上使用 .then() 。请注意,我切换到 .then(),这是使用 promise 的 ES6 标准方式(并受 jQuery 支持),而不是使用 jQuery 特定的 .done().