Promises
If you aren't familiar with promises as a concept then you have two choices: a) follow instructions and use the code to get a desired effect, without a deep understandign of why it works, or b) brush up: https://www.promisejs.org/
There are many prominent libraries that implement the concept of a promise
. Our favorite in this tutorial will be bluebird.
To install this module, run the commands:
in the terminal now.
The really really long running discussion around adding support for promises within loopback server side code and the changelogs, let us draw the following semi-sure conclusions:
a) If you are running on Node.js version 0.10.x
, then you need to add the following line to the top of your main server/server.js
file to tell LoopBack which Promise implementation to use: global.Promise = require('bluebird');
b) Version 2.19.0
of loopback-datasource-juggler
was the first version to add Promises to DAO.
c) Version 2.24.0
of loopback-datasource-juggler
was the first version that added further by promisifying model relation methods.
d) In [package.json](open_file loopback-zero-to-hero/package.json panel=1 ref="loopback-datasource-juggler") we use Version 2.32.0
of loopback-datasource-juggler
, its sufficient to say that the CRUD methods for models and relatedModels now use promises ... but something like UserModel.login()
still does not!
e) Let us promisify what the framework hasn't. Open [user-model.js](open_file loopback-zero-to-hero/common/models/user-model.js") and update it:
f) Next, create 03-login-users.js: touch ~/workspace/loopback-zero-to-hero/server/boot/03-login-users.js
g) Then add the following to 03-login-users.js:
|||info
info
Note the use of UserModel.loginAsync()
and .tap()
, both of which are made possible by the use of bluebird
|||
h) Now run and observe the logs:
i) You can now use the access token spat out in the log lines: logged in w/ token ...
where long strings like: iumwgdnjmkavYYADlYF5miDA0d1pFWf13Dlzgvm7p9ptkRihSIi9PwkDJxtsc97H
represent an accessToken.
Last updated