How to set ajax timeout for Ember.RSVP or store.findRecord?

Is there a way to set a timeout for Ember.RSVP promises or store.findRecord requests?

I know it’s calling $.ajax under the hood, so I could use something like Ember.$.ajaxSetup({ timeout: 5*1000 }) in an initializer, but I was curious if there was a better way.

Ideally I’d like to set timeouts for the RSVP promises of certain routes, but not others, and I’d prefer to fetch the data using ember-data (not a jquery ajax call).

1 Like

You should avoid coupling promises to timeouts as this can result in unexpected side effects. Isn’t that the whole idea of promises in the first place? Try rethinking the design of your application first.

Just to bump this - can you expand? How do you deal with the following:

  1. Making an Ember Data request (via findRecord, findAll, etc) to an external API
  2. Enforcing a timeout to 'bail out" if the promise isn’t resolved in X seconds (or ms, rather)
  3. Turning this into an error for the route to handle or bubble up

If this isn’t to be handled on the model’s promise then where should be handled?

1 Like

This seems like a pretty common use case. What is the established way to handle this in Ember, or are we expected to hack jquery to accomplish this?

I think it should be as simple as something like overriding the ajaxOptions in the Rest Adapter (though, this is a Private API, so use with caution!).

// app/application/adapter.js
import DS from 'ember-data';

export default DS.RestAdapter.extend({
  ajaxOptions(url, type, options) {
    let hash = this._super(url, type, options);
    hash.timeout = 5000;
    return hash;
  }
});

Also, it’s worth noting that there’s a bunch of conversations on this. Once Ember moves away from using jQuery’s Ajax and (perhaps) uses the new fetch API, this may no longer be an option.

https://github.com/whatwg/fetch/issues/20

2 Likes

Thanks! Your solution works great, and I’m happy to hear that it’s being considered as part of the public api in the future.