$q – Promises in Javascript

$q is a service in AngularJS that helps a developer run functions asynchronously, and use their return values which are promised, when the asynchronous function has finished processing.

A promise is a special type of Object that we can either use, or construct ourselves to handle asynchronous tasks. We deem them promises because we are “promised” a result at a future point in time. For example an HTTP call could complete in 200ms or 400ms, a promise will execute when resolved

A promise is said to be fulfilled when we get a result from a particular action. Conversely, a promise is said to be rejected when we do not receive a response

Deferred API

A new instance of deferred is constructed by calling $q.defer()

A deferred object can either be fulfilled using .resolve(data) or rejected using .reject(error)

Promise API

A new promise instance is created when a deferred instance is created and can be retrieved by calling deferred.promise. The purpose of the promise object is to allow for interested parties to get access to the result of the deferred task when it completes.

 

A call to a function that returns a promise should have a .then() function that receives an inline function to execute when the promise is returned.

The function that returns a promise should hook off to the service/endpoint it’s connecting to etc to get data, and have it’s own then() function that contains an inline function to execute when the actual data is returned.

http://andyshora.com/promises-angularjs-explained-as-cartoon.html

https://toddmotto.com/promises-angular-q

http://haroldrv.com/2015/02/understanding-angularjs-q-service-and-promises/

https://docs.angularjs.org/api/ng/service/$q

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s