A
A
Artem2017-06-18 11:54:47
Node.js
Artem, 2017-06-18 11:54:47

How to return a value from callbacks or terminate an external function?

Hello.
I'm trying to understand Node.js, for this I'm writing a server application - Web API.
In request handlers, the following construction is now encountered:

create(req, res, next) {
        crypt('PASSWORD').hash(function(err, hash) {
            if (err) {
                next("ERROR!");
                // ! Здесь нужно завершить дальнейшее выполнение ф-ии create()
            }
            
            var newUser = new users.User();
            
            newUser.save(function (err) {
                if (err) {
                    next("ERROR!");
                    // ! Здесь нужно завершить дальнейшее выполнение ф-ии create()
                } else {
                    res.send("User has been saved!");
                }
            })
        });
    },

I see the following problems:
1. It is necessary to complete the create function from the callbacks (see comments in the code), I don’t understand how to do this.
2. Too much nesting. How can it be reduced?
I would like to see something like this:
create(req, res, next) {
   var _hash = '';
   crypt('psw').hash(hash => {
      if (hash) {
         _hash = hash;
      }
   }
   users.User().save(err => {
      // Do something..
   }
}

I read about closures and asynchronous work, but I can’t organize the code correctly.
I ask for your help. Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
emp1re, 2017-06-19
@ber_enot

create(req, res, next) {
        crypt('PASSWORD').hash((err, hash) => {
           if (err)  return next(err);
           new User().save((err) => {
                if (err) return next(err);
                res.send("User has been saved!");
            })
        });
    },

else you don't need either

R
RidgeA, 2017-06-18
@RidgeA

https://developer.mozilla.org/en/docs/Web/JavaScri...
https://developer.mozilla.org/en/docs/Web/JavaScri...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question