JavaScript Battery API: Promises

By  on  

Working at Mozilla has afforded me the time to look at new APIs, one of them being the Battery API.  I wrote about the Battery API a while back, when the API was fresh into browsers.  Since then the Battery API has changed, implementing a promise-based API which is now available only in Google Chrome.  Let's have a look at how to use the new API!

The functionality we need is still hosted on the navigator object, but this time it's a function called getBattery:

navigator.getBattery().then(function(result) {});

A promise is returned from the getBattery() call, and the callback provided to then is given a BatteryManager object which provides the following example information:

// result:
BatteryManagery {
	charging: false,
	chargingTime: Infinity,
	dischargingTime: 8940,
	level: 0.59,
	onchargingchange: null,
	onchargingtimechange: null,
	ondischargingtimechange: null,
	onlevelchange: null
}

The new API is different in execution but likewise in result. Remember that the old API had issues with Mac device batteries, and that doesn't seem to have changed.  Accommodating for different browser prefixes is a pain but something we've come to accept, but it really sucks when the methodology is completely different.  Let's hope that other browser vendors are quick to update and we can see a unified, browser-prefixed (banter) API again.

Recent Features

  • By
    CSS @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

  • By
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

Incredible Demos

  • By
    Animated AJAX Record Deletion Using MooTools

    I'm a huge fan of WordPress' method of individual article deletion. You click the delete link, the menu item animates red, and the item disappears. Here's how to achieve that functionality with MooTools JavaScript. The PHP - Content & Header The following snippet goes at the...

  • By
    MooTools Fun with Fx.Shake

    Adding movement to your website is a great way to attract attention to specific elements that you want users to notice. Of course you could use Flash or an animated GIF to achieve the movement effect but graphics can be difficult to maintain. Enter...

Discussion

  1. MaxArt

    Wow, yeah, promises are pretty cool, awesome!

    … No, not really in this case.

    Previously we could retrieve all those properties synchronously. May I guess the change has been made because it’s not always possible to get the value synchronously? I hope we’re not making everything asynchronous just for the sake of it.

    Another slightly related thing is the method’s name: getBattery. When I want to get something, I want it “right here, right now”. Synchronously. If it’s asynchronous, if I’m getting a promise that can fail, then I’m making a *request*. A better name would have been queryBattery or inspectBattery, then.

    • I mostly agree. I think the idea is that an ideal world makes everything asynchronous, but why the Battery API needs to be Promised-based is beyond me. But I’m sure people smarter than us know why :)

    • MaxArt

      A lot of new things in Javascript is getting this asynchronous nature. It’s the new trend. Most of the times it’s a *good* thing indeed. But now I’m thinking about older stuff and how it could have been conceived today. For example:

      // Callback as the second argument
      document.querySelector("#myElement", function(result) {
          // Promise-style
          result.queryComputedStyle().then(function(style) {
              ...
          });
      });
      

      Just… wow. I wonder if with all the experience we have today the DOM could have been something better than the current utter mess.

  2. Amazing. Thanks

  3. Drew

    It’s probably possible to normalize the functionality a bit by taking the non-promise based apis and converting them into promises in whatever function is normalizing all the browser prefix versions.

  4. Jas

    I apologize for necroing, I just wanted to point out that getting battery data requires an external call which means that we’re at the mercy of whatever that external call does and if getBattery() is synchronous, and for whatever reason takes longer than expected to complete, we have now blocked the main javascript thread -> frozen web page.

    Whenever we want to make an external call, i.e. database, web api, get battery info, anything that is not within the context of a web browser…etc., we should be making that call asynchronously.

    Now, since we have to make asynchronous calls, promises is currently the best way to handle them. I really don’t think anyone of us wants to go back to the days of callback hell (not to be confused with promises, which MaxArt seems to have done).

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!