Return 一个空洞的承诺

Return an empty promise

我有一个 return 是 jQuery 承诺的功能。它看起来像这样:

addBooks(books: Array<Books>) {
    return $.ajax({
        url: '/Books/AddBooks/',
        type: 'POST',
        data: ko.toJSON(books),
        contentType: 'application/json'
    });
}

我这样做是为了重用这个函数和链式承诺回调,例如:

addBooks.done(() => { alert("Books added!"); })

我的问题是,如果我想提前脱离 addBooks 并防止访问服务器怎么办。例如:

addBooks(books: Array<Books>) {

    // An empty array was passed in for some reason.
    // Theres nothing to add so dont try to POST
    if (books <= 0) return null;

    return $.ajax({
        url: '/Books/AddBooks/',
        type: 'POST',
        data: ko.toJSON(books),
        contentType: 'application/json'
    });
}

我的示例无法编译,因为我的链式完成回调示例需要 addBooks 到 return 一个 promise 对象,而不是 null。我怎么能 return 一个空洞的承诺(或者在这种情况下我应该 return 的任何正确对象)?

你可以return一个解决承诺:而不是

if (books <= 0) return null;

使用

if (books <= 0) return $.Deferred().resolve();

注意,不过,jQuery的Promise API做了一些令人惊讶的事情:有时它调用你的done /then/等。与 done/then/等同步回调。打电话,有时没有。大多数承诺库确保调用始终是异步的,即使您正在调用 done/then/等。在一个解决的承诺。 jQuery 没有,所以你会得到细微的差别。

例如,这段代码:

addBooks(() => console.log(1));
console.log(2);

...将记录

2
1

...如果您拨打了 ajax 电话,但是

1
2

...如果您 return 已解决承诺。

How can I return an empty promise (or whatever the correct object is I should return in the situation)?

是的,"empty promise" 在这里是合适的,如果你的意思是一个已经实现但什么也没有实现的承诺(undefinednull)。

创建这样的 jQuery 语法是使用 $.when 和一个(或没有)参数:

if (books <= 0) return $.when(null);

来自https://api.jquery.com/jquery.when/

If you don't pass it any arguments at all, jQuery.when() will return a resolved promise.

例如

if (books <= 0) return $.when();

并且,如果您需要传递的值不是未定义的:

If a single argument is passed to jQuery.when() and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately. The doneCallbacks are passed the original argument.

例如传递了一个空数组:

if (books <= 0) return $.when([]);

例如传递了一个空对象:

if (books <= 0) return $.when({});