2

I'm using D.js as promise library for our javascript application. Following is my sample code:

function getData(deferred) {
  var data_one;

  // getInfo is returning a promise for async task
  getInfo()
   .then(function (resp_one) {
      data_one = resp_one;
      // getInfo2 is also returning another promise
      return getInfo2();
   })
   .then(function (resp_two) {
     deferred.resolve('prefix' + data_one + resp_two);
   });
};

function sample () {
  var d = D(),
    data = localStorage.getItem('key');

  if (data) {
    d.resolve(data);
  } else {
    getData(d);
  }
  return d.promise;
}

sample().then(function (data) {
  //do something with data.
});

I im invoking sample function. Is the implementation inside the sample function and sub functions following the coding standard for promises? Im new to promises, Is it good to passing around deferred object to other function to resolve/reject ?? Is there any better way to implement the above functionality??

Thanks in advance..

bijoshtj
  • 299
  • 4
  • 14

1 Answers1

2

Looks like you can improve the code if you use promises in more natural way.

First of all if getData returns a Promise then you don't have to pass deferred around, this is considered anti-pattern. You just simply return getInfo().

Another thing, in the sample function if your data might be already available it's convenient to use D.promisify method to return resolved promise with non-promise value:

function getData() {
    var data_one;
    return getInfo().then(function (resp_one) {
        data_one = resp_one;
        return getInfo2();
    })
    .then(function (resp_two) {
        return 'prefix' + data_one + resp_two;
    });
};

function sample() {
    var data = localStorage.getItem('key');
    return data ? D.promisify(data) : getData();
}

sample().then(function (data) {
    //do something with data.
});
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • Hi , thank you for the quick response. There is a bit modification in my scnerio. I modified getData method . Please give a look into. Sorry for inconvenience. :) – bijoshtj Feb 12 '15 at 13:09