Promises are an alternative for asynchronous operations that can be simpler to write and understand than traditional callback-based approaches. Promises also enable you to handle asynchronous errors with something similar to a synchronous
What is a promise?
A promise represents the result of an asynchronous operation. A promise is in one of the following states:
- pending - The initial state of a promise (neither fulfilled nor rejected).
- fulfilled - The action relating to the promise succeeded. When a successful promise is fulfilled, all of the pending callbacks are called with the value. If more callbacks are registered in the future, they will be called with the same value. Fulfillment is the asynchronous analog for returning a value.
- rejected - The action relating to the promise failed. When a promise is rejected it invokes the errbacks that are waiting and remembers the error that was rejected for future errbacks that are attached. Rejection is the asynchronous analog for throwing an exception.
- settled - The promise has been fulfilled or rejected. Once a promise is settled, it is immutable (it can never change again).
- Callback: A function executed if a a promise is fulfilled with a value.
- Errback: A function executed if a promise is rejected, with an exception.
- Progressback: A function executed to show that progress has been made toward resolution of a promise.
When using Node v0.12+ or io.js 1.0+, you can use the native global Promise object.
With earlier versions of Node, use Bluebird. When running in an environment that supports native promises, Bluebird will automatically "fall back" to use them, so typically, it's easier to set up Bluebird so you don't need to be concerned with platform support. Simply, enter this command to update your application's dependencies in
Then, in your code:
Promises in LoopBack
For example, here is how you would call a CRUD operation on a model that extends PersistedModel with standard callbacks:
With promises, you would instead do the following:
Promises can simplify, for example, defining asynchronous remote methods. Instead of:
With promises, this is reduced to:
- Promises (by Forbes Lindsay)
- Promise (Mozilla Developer Network)