Returning Deferred

Take advantage of the Deferred objects returned by jQuery’s $.ajax methods. In remotedatastore.js, update the prototype methods so that they return the result of calling $.get, $.post, and $.ajax.

...
  RemoteDataStore.prototype.add = function (key, val) {
    return $.post(this.serverUrl, val, function (serverResponse) {
      console.log(serverResponse);
    });
  };

  RemoteDataStore.prototype.getAll = function (cb) {
    return $.get(this.serverUrl, function (serverResponse) {
      console.log(serverResponse);
      cb(serverResponse);
    });
  };

  RemoteDataStore.prototype.get = function (key, cb) {
    return $.get(this.serverUrl + '/' + key, function (serverResponse) {
      console.log(serverResponse);
      cb(serverResponse);
    });
  };

  RemoteDataStore.prototype.remove = function (key) {
    return $.ajax(this.serverUrl + '/' + key, {
      type: 'DELETE'
    });
  };
...

Because they now return the Deferred produced by jQuery’s Ajax methods, it is not absolutely necessary for get and getAll to accept callbacks. To account for the possibility of no callback, add an if statement to check that cb was passed in before invoking it.

...
  RemoteDataStore.prototype.getAll = function (cb) {
    return $.get(this.serverUrl, function (serverResponse) {
      if (cb) {
        console.log(serverResponse);
        cb(serverResponse);
      }
    });
  };

  RemoteDataStore.prototype.get = function (key, cb) {
    return $.get(this.serverUrl + '/' + key, function (serverResponse) {
      if (cb) {
        console.log(serverResponse);
        cb(serverResponse);
      }
    });
  };
...

Save remotedatastore.js. Since the RemoteDataStore methods return Deferreds, you will need to update the Truck methods to do the same. For now, you will focus on createOrder and deliverOrder.

Open truck.js and add a return to these two methods where you call them on this.db.

...
  Truck.prototype.createOrder = function (order) {
    console.log('Adding order for ' + order.emailAddress);
    return this.db.add(order.emailAddress, order);
  };

  Truck.prototype.deliverOrder = function (customerId) {
    console.log('Delivering order for ' + customerId);
    return this.db.remove(customerId);
  };
...

Save truck.js. Truck now returns the Deferreds that RemoteDataStore produces. When using Promises and Deferreds, it is a best practice to return them from your functions. Returning them lets any object that calls createOrder or deliverOrder register callbacks that are triggered when the asynchronous work is finished.

In the next section, you will do just that.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.2.225