NodeJS SDKs will now return promises in endpoint calls, as an alternative to accepting callbacks.
- We use ES6 Promises which is based on Promises/A+ and is interoperable with most Promise-based implementations.
- Callbacks are still supported (for backward-compatibility) but are now optional.
Re-generate your NodeJS SDK to get the new Promise-enabled SDK implementation now.
Why Promises?
Here is an except from a blog by StrongLoop:
Callbacks are the simplest possible mechanism for asynchronous code in JavaScript. Unfortunately, raw callbacks sacrifice the control flow, exception handling, and function semantics familiar from synchronous code. Promises provide a way to get those things back.
Usage
All endpoint methods now return Promises.
let promise = apiController.endpointMethod();
promise.then(onFulfilled, onRejected);
onFulfilled
method is called if the endpoint call succeeds andonRejected
is called upon error.onFulfilled
method will be passed a response from theendpointMethod
if any, after validation.onRejected
method will be passed an error object containing anerrorMessage
anderrorCode
or a custom error object if defined by your API description.
The sample code above can also be rewritten as:
apiController.endpointMethod()
.then(onFulfilled)
.catch(onRejected);
Order of callback execution
An endpoint call's callback is always executed before its Promise is resolved.