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: any) {
return async2().fetch();
})
.then(function onSuccess(anotherResponse: any) {
// ...
})
.catch(function onError(anyError: any) {
// ...
});
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.
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.
const stream = observableFn()
.subscribe(function onNext(response: any) {
// ...
}, function onError(error: any) {
// ...
}, 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.
asyncFn()
.then(function onSuccess(response: any) {
return observableFn().toPromise();
})
.then(function onSuccess(response: any) {
// ...
})
.catch(function onError(error: any) {
// ...
});
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:
- Callbacks, Promises, and Coroutines. Presentation about asynchronous programming patterns in JavaScript.
- Promises/A+ spec. The specification as adopted by the library.
- Observables. The specification as adopted by the library.
- Transform Observables to Promises.