1

In my REST application I try to fetch data using http GET method. As a response I get an object with responseText and responseJSON fields as below:

Object {readyState: 1}
abort: ( statusText ) {
always: () {
complete: () {
done: () {
error: () {
fail: () {
getAllResponseHeaders: () {
getResponseHeader: ( key ) {
overrideMimeType: ( type ) {
pipe: ( /* fnDone, fnFail, fnProgress */ ) {
progress: () {
promise: ( obj ) {
readyState: 4
responseJSON: Array[3]
responseText: "[{"id":1,"name":"Standard"},{"id":2,"name":"Small (32 cm)"},{"id":3,"name":"Big (42 cm)"}]"
setRequestHeader: ( name, value ) {
state: () {
status: 200
statusCode: ( map ) {
statusText: "OK"success: () {then: ( /* fnDone, fnFail, fnProgress */ ) {
__proto__: Object 

When I try to store responseText or responseJSON in a variable, it results in an "undefined" error in a console. Here's a fragment of the code:

define([
    'backbone'
],
    function (Backbone) {
        'use strict';

        return Backbone.Collection.extend({
            initialize: function () {
                this.sizes = this.fetch();
            },

            url: 'http://localhost:8080/sizes',

            getContext: function () {
                var sizelist = this.sizes.responseJSON;
                return sizelist;
            }
        });
    });

Variable "sizelist" is undefined, when I try to do a console.log(), although "this.sizes" is an object presented above. The question is how to get to the data stored in responseJSON or responseText field. Any help appreciated.

  • 3
    possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Andreas Jul 06 '15 at 14:19
  • Why do you have `sizes` in `this.sizes.responseJSON`? I would think you would just access `responseJSON` property (i.e. `this.responseJSON`). – Mike Brant Jul 06 '15 at 14:29

1 Answers1

0

You need to wait that the query has finished to fetch

       function () {
            var self = this;
            this.fetch({
                success: function(response) {
                    // store your response from here
                    self.sizes = response;
                }
            });
        }
François Richard
  • 6,817
  • 10
  • 43
  • 78