Sai Sai - 1 month ago 4
Javascript Question

Using JavaScript Promises in APIs

I am new to the concept of Promises in JavaScript. I have an app that offers APIs to other components.

My Goal: instead of using traditional callback based approach for asynchronous operation, I want to use Promises. I am presenting an example below:

requestCurrentPosition (correlationId, options)


Currently this is an async operation that passes a coorelation ID. When the operation completes, success or failure callback can be called:

failure(response, correlationId)
success(response, correlationId)


This API will now be refactored as below:

requestCurrentPosition (Promise, options)


Is this the correct approach? If yes, how will the callback function be notified?

Answer

The usual approach would be to return a promise:

var promise = requestCurrentPosition(options)

This allows for a usage like so:

requestCurrentPosition(...)
  .then(function(){...})
  .catch(function(){...});
Comments