Google APIs Adopt Promises
Written by Ian Elliot   
Friday, 03 October 2014

Promises seem to be the way that every JavaScript framework is heading. The latest to embrace the Promise is Google's JavaScript Client Library.

googledevicon

 

The Google JavaScript Client Library is still in beta but it is the unified way to access most, but not all, Google APIs - for example, it doesn't support Maps or Earth. The idea is that a single library provides all of the authentication and security needed to access Google's server. For simple requests just a Google key is necessary. For requests that access private data, hovever, an OAuth 2 transaction is required. 

As with all JavaScript APIs that rely on Ajax style requests, the big problem in writing clear, easy-to-understand code is the proliferation of callbacks. The most commonly promoted solution to this is the use of the Promise.

The Promise is an object returned by the API call which holds the state of the call - pending, fulfilled or rejected. You can use the Promise object's methods, usually then, to specify what should happen when the state changes to fulfilled or rejected. 

The original version of the library was based on callbacks, but a measure of backward compatibility has been maintained in the transisiton to Promises. The methods only return a Promise object if a callback function isn't supplied. 

googleapiexplore

The key advantage of Promises is that requests can be chained in a fluent style and this makes the code more readable because it is closer to the flow of control that corresponds to the asynchronous process if each call was blocking. 

The uptake of Promises is a good thing and, as they are in the ECMAscript 6 language spec, you can expect them to become increasingly the standard way to handle async in JavaScript. 

However Promises are still a low level construct and there are better ways to deal with the problem such as the async and await constructs found in C#. This restores the synchronous flow of control to an asynchronous sequence of calls and takes the burden completely off the programmer and places it on the JavaScript engine. Currently proposals for async and await in JavaScript are targeted at ECMAscript 7. Let's hope we all don't waste too much time on Promises before they arrive.

 googledevicon

Banner


Google Updates Responsible AI Toolkit
01/11/2024

Google has announced updates to the Responsible Generative AI Toolkit to enable it to be used with any LLM model. The Responsible GenAI Toolkit provides resources to design, build, and evaluate open A [ ... ]



C23 ISO Standard Is Here But You Probably Won't Read It
06/11/2024

At last ISO C23 has been published, but at $250 you probably aren't going to read it. Can we really tolerate this sort of profiteering on the work of others? This is worse than academic publishing!


More News

 

espbook

 

Comments




or email your comment to: comments@i-programmer.info

 

Last Updated ( Friday, 03 October 2014 )