K
K
Kappy2018-11-30 12:30:26
Node.js
Kappy, 2018-11-30 12:30:26

How to pass an Express handler?

There is a get handler

router.get('/', function(req, res, next) {
...Тут действия с бд 
next();
}

Next, I pass the handler to the next level
router.get('/', function(req, res, next) {
...Тут следующие действия
next();
}

But for some reason, the promise does not work, and the 2nd block is executed immediately, only then the 1st. I do the same as in the documentation, it doesn’t help, I’m still learning a little and I stuck here. I want to fill in json in one handler, in the second pass .

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
shmatuan, 2018-11-30
@KappyJS

next(); should be called in the callback / then of the asynchronous function The
database has not yet returned a value (only sent), and next() has already worked

router.get('/', function(req, res, next) {
  someaction({query}, (error, data) => { // тут от БД зависит, может быть через промисы
    if(data) next();
  })

}

A
Alexander Drozdov, 2018-11-30
@bagzon

Well, are you calling next() inside the promise?

E
Egor Petrov, 2018-12-06
@chel1

router.get('/', async function(req, res, next) {
    try {
        await someaction(query);
        next();
    }
    catch(error){
        console.error(error);
    }
  })
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question