ave
ave

Reputation: 47

Uncaught (in promise) when calling multiple ajax within router model

I calling multiple API endpoint within ember router model I'm using ember-cli 3.11.0 When I refresh the page, it failed to load with "Uncaught (in promise)" which point specifically in $.ajax call

import $ from 'jquery';
import { hash } from 'rsvp';

export default Route.extend(AuthenticatedRouteMixin, {
  model: function (param) {
    return hash({
      category: $.ajax({
        url: 'http://localhost:8000/catalog/category/' + param.id,
        type: 'GET'
      }).then(function(res) {
        return res;
      }),
      categories: $.ajax({
        url: 'http://localhost:8000/catalog/category',
        type: 'GET'
      }).then(function(res) {
        return res;
      })
    })
  }
});

With those codes, I want to call inside setupController something like

setupController(ctrl, model) {
   console.log(model.category);
   console.log(model.categories);
}

Upvotes: 1

Views: 251

Answers (1)

real_ate
real_ate

Reputation: 11289

Ola @ave 👋 thanks for your question!

As @jelhan mentions in their comment to you, it is recommended that you use fetch now as it is a much more modern API than using $.ajax() from jQuery.

If you need to support older browsers like IE11 I would recommend installing ember-fetch by following the README instructions on https://github.com/ember-cli/ember-fetch which is essentially just the following:

ember install ember-fetch

Then you can update your example to be the following:

import Route from '@ember/routing/route';
import fetch from 'fetch';
import { hash } from 'rsvp';

export default Route.extend(AuthenticatedRouteMixin, {
  model(param) {
    return hash({
      category: fetch('http://localhost:8000/catalog/category/' + param.id)
        .then((res) => res.json()),
      categories: fetch('http://localhost:8000/catalog/category')
        .then((res) => res.json()),
    })
  }
});

Now for your actual error, I would imagine that the error that you are seeing with "Uncaught (in promise)" is that actually one of these requests is failing for some reason 🤔 I would recommend adding an error page following the Error Substate documentation and for the template include the following

{{log 'my error' model}}

this will effectively console.log() the error that you are getting back from your route and you will get more information about what is wrong 👍

Upvotes: 2

Related Questions