Skip to content Skip to sidebar Skip to footer

Backbone + Promises - How To Fetch After Post

I have a model which has two functions - one posts, and one gets. The fetch: fetch: function (options) { var self = this; return P1Comm.get({ 'dataType': 'json', 'proc

Solution 1:

The reason you get the error is because your acceptTerms doesn't return anything, or in other words returns undefined which doesn't have a then() method.

Your code should be something like:

fetch: function(options) {
    var self = this;
    return P1Comm.get({
      dataType: 'json',
      processAjaxResponse: self.processAjaxResponse,
      onStatusInvalid: function(e) {
        P1.log(e, 'status');
      },
      onSuccess: options.success,
      onError: function(e) {
        P1.log(e);
      },
      sourceURL: P1.API_APPS_ROOT + 'v1.0/accepted-terms'
    });
},

acceptTerms: function(appId) {
    var self = this;
    self.set({
      'app_id': parseInt(appId, 10)
    });

    return self.createEdit(self.toJSON(), {}).pipe(function() {
    //---------------------------------------^ better use .then()var saveOpts = {
        dataType: 'json',
        stringify: true,
        contentType: 'application/json',
        processData: false,
        processAjaxResponse: self.processAjaxResponse
      };
      return self.save(self.toJSON(), saveOpts);
    });
},

This code asummes that P1Comm.get, self.createEdit and self.save returns a promise object. If they don't then you need to create a Deferred object and return it's promise from these functions. And inside the success/error callbacks of their asynchronous actions you need to resolve/reject the promise accordingly.

I'd also like to mention that .pipe() is a deprecated method, you should use then() unless you're using ancient version of jQuery.

Post a Comment for "Backbone + Promises - How To Fetch After Post"