Promises, Promises

Cooper Temple Clause references aside, Promises are a subject I have (ahem) promised myself to document for a while.

I have had an interesting relationship with them, avoiding them this year on a recent Node.js project until I felt everyone was comfortable with callbacks. So they’ve always been there, and my first usage of them was to begin rewriting a chrome plugin called cookieflip I previously created. This project which was conspicuous in my very strict usage of callbacks, but I felt like I went too far and that promises would allow me to cut back the amount of code used.

Let’s compare -

it('Load the active tab to get the current url', function () {

            var dummyTabs = [];

            dummyTabs.push({url: 'testurl1'});
            dummyTabs.push({url: 'testurl2'});
            dummyTabs.push({url: 'testurl3'});

            chrome.tabs.query.withArgs({active: true, currentWindow: true}).yields(dummyTabs);

            cookieFlip = new CookieFlip();

            return cookieFlip.getUrlOfCurrentTab().then(function (url) {

                chai.assert.equal(url, 'testurl1');


  it("should get the currenttab and pass in the next callback", function () {

        var cookieFlip = new CookieFlip(debug);

        spyOn(cookieFlip, 'getCurrentTab');


          //should verify the method parameters here but jasmine sucks at that

      describe("when querying chrome for the active tab", function() {

        it("should return the first tab to the returnMobileCookie callback", function () {

          chrome.tabs = chrome.tabs || {}
          chrome.tabs.query = chrome.tabs.query || {}
          chrome.tabs.query = jasmine.createSpy("query spy");


            {active:true,currentWindow:true }, 

        // final test that the tabs are returned to the callback

I’m clearly working way too hard in the callback example to achieve a similar goal. The key part is not having to worry about what to do next, just concentrate on returning what we need. Like driving with a brake pedal after not having one!

These are just rough thoughts, I think the biggest improve really comes when you start use promises with Http request libraries. That’s for the next blog post!