Sai
Sai

Reputation: 2109

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?

Upvotes: 0

Views: 109

Answers (1)

Pasukaru
Pasukaru

Reputation: 1095

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(){...});

Upvotes: 1

Related Questions