Advertisement
ByMsx

Promises

Mar 19th, 2018
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* if we're doing function with promises, we must return it */
  2.  
  3. function findUser (login, password) {
  4.     return db.models.user.find({ // here we MUST return promise
  5.         login: login,
  6.         password: password
  7.     });
  8. }
  9.  
  10. findUser('example', 'examplepw').then(function (user) {
  11.     // Do something with user.
  12. });
  13.  
  14. /* So if 'return' missed */
  15.  
  16. function findUserWrong (login, password) {
  17.     db.models.user.find({
  18.         login: login,
  19.         password: password
  20.     });
  21. } // if not 'return' specified, function returns 'undefined'
  22.  
  23. findUserWrong('example', 'examplepw').then(function (user) { // function throws an error, because 'undefined' haven't any functions
  24.     // Do something with user.
  25. });
  26.  
  27. // even if we will write in async context
  28. let user = await findUserWrong('example', 'examplepw'); // user will be undefined, because function returns 'undefined'
  29.  
  30. /* Complete example with ES6 */
  31.  
  32. function findUser (login, password) {
  33.     return db.models.user.find({
  34.         login,
  35.         password
  36.     });
  37. }
  38.  
  39. findUser(login, password)
  40.     .then(user => {
  41.         // Do something...
  42.     });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement