Translation last updated: 17 Nov 2015.
This documentation is for LoopBack 2.x.
For the latest information, see the LoopBack documentation in English.
Skip to end of metadata
Go to start of metadata
Icon

Promise support in LoopBack is not complete. See LoopBack issue #418 for current status.

PLEASE NOTE: This documentation is a work in progress.

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 try/catch block.

REVIEW COMMENT from Rand

See #1409, #1575 and #418.

Link to list of "TO DO" items in the issue.

Add explanation of why you might want to use Promises in LB, e.g. remote method

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).

Additional terminology:

  • 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.

Setup

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 package.json:

Then, in your code:

Promises in LoopBack

Icon

If using CoffeeScript, make sure your models don't accidentally return a Promise.

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:

Another example:

Promises can simplify, for example, defining asynchronous remote methods.  Instead of:

common/models/my-model.js

With promises, this is reduced to:

common/models/my-model.js

References

See also:

 

  • No labels