Return an empty promise

Jonathan Eckman picture Jonathan Eckman · May 2, 2015 · Viewed 20.7k times · Source

I have a function that returns a jQuery promise. It looks like this:

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

I do this so I can reuse this function and chain promise callbacks like:

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

My question is, what if I want to break out of addBooks early and prevent a trip to the server. For example:

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'
    });
}

My example will not compile because my chained done callback example is expecting addBooks to return a promise object, not null. How can I return an empty promise (or whatever the correct object is I should return in the situation)?

Answer

Bergi picture Bergi · May 2, 2015

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

Yes, an "empty promise" is appropriate here, if you mean a promise that is already fulfilled with nothing (undefined, null).

The jQuery syntax to create such is using $.when with a single (or no) argument:

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