SDK Concepts

This guide explains the concepts of the JavaScript library. It primarily discusses how asynchronous flows are managed using promises.

Promises

Promises provide a new way of dealing with asynchronuous flows in JavaScript.

async1().then(function onSuccess(response) {
  return async2().fetch();
}).then(function onSuccess(anotherResponse) {
  doSomething();
}).catch(function onError(anyError) {
  alert('Something went wrong.');
});

The then function can accept one or two arguments: the first is a function invoked on success, the second is a function invoked on error.

The catch function accepts one argument: a function invoked on error.

The example above will have the exact same eventual result as the nested callback example. However, the code looks much more clean, and especially dealing with erroneous states has become much easier.

Internally, the library relies on promises to deal with asynchronous flows.

The library internally uses AngularJS’s $q for promises. This way, there is no need to manually maintain the scope life cycle. The following ‘just’ works:

var myApp = angular.module('myApp', ['kinvey']);
myApp.controller('TestCtrl', ['$scope', '$kinvey', function($scope, $kinvey) {
    $kinvey.ping().then(function(response) {
        $scope.response = response;
    });
}]);

Observables

When dealing with asychronous functions, sometimes you need to return data before the asychronous function has completed. Observables provide a way to execute asychrounous flows in JavaScript that need to return data several times.

var stream = observableFn();
stream.subscribe(function onNext(response) {

}, function onError(error) {

}, function onComplete() {

});

The subscribe function accepts three arguments: the first is a function invoked when new data is available, the second is a function invoked on error, and the third is a function invoked when the asychronous process is complete.

Any error thrown in the onNext function will cause the onError function to be called with that error and the observable to be unsubscribed.

Internally, the library relies on observables to deal with asynchronous flows that could possibly return data several times.

Transform Observable into a Promise

Sometimes you will need to mix and match functions that return observables and promises. When this happens it might be useful to transform your observable streams into promises.

var promise = asyncFn();
promise.then(function onSuccess(response) {
  var stream = observableFn();
  return stream.toPromise();
}).then(function onSuccess(response) {

}).catch(function onError(error) {
  // ...
});

When you transform an observable stream into a promise, the response that would have been returned as the last response to the onNext function will be the response returned to the onSuccess function of the promise.

Learn more

If you are interested in learning more about promises or observables, we recommend reading the following articles: