David Goldfarb
David Goldfarb

Reputation: 1886

Returning promise instead of jquery ajax call

I have a function that is expected to call jquery.ajax, and return it as a promise for further processing.

But, sometimes, it has enough information to proceed synchronously, without the ajax call. It still needs to return a promise, to fulfill its contract with callers. What is an idiomatic way to do this?

E.g.

function f(x) {
  return x? 
    $.ajax({url: "http://myServer", data: x, ...})
    : /* what should be here? */;
}

Upvotes: 1

Views: 406

Answers (1)

Bergi
Bergi

Reputation: 664538

To create a fulfilled jQuery promise, you can use jQuery.when:

return $.when(…);

To create a rejected jQuery promise, you'll need to use something a bit more complicated (but at least you can chain it):

return $.Deferrred().reject(new Error(…)).promise();

Upvotes: 1

Related Questions