Promises Sequential - Node

Asked

Viewed 199 times

0

I am trying to create a string of sequential Promises in Node.js and it is not running one at a time but all!

You should perform as follows:

Promise1 -> (then) -> Promise2 -> (then) -> Promise3 ...

But in my case, he’s running them all at once. The code is as follows::

router.post('/entrega', (req, res) => {

    let pedido = new PedidoDao(req.body);

    Promise.resolve(pedido.isEntregue())
    .then(pedido.setEntrega())
    .then(responseSuccess())
    .catch( err => responseError(err))

    function responseSuccess(){
        res.json({status:true, message: 'Entrega realizada com sucesso.'});
    }

    function responseError(message){
        res.json({status:false, message: message});
    }

});

All Pedidodao functions return a Promise(resolve, Reject).

I made the setEntrega() function return a purposeful Reject, but still the responseSucces function runs face to face. After 1 second pops the Reject of the setEntrega function and falls in catch, but there has already been a successful response in the API.

I may be traveling, but I didn’t want to use async/await to do this kind of sequencing. It will be possible to do it with Promise or not?

Hug.

EDIT: Possible solution I made this edition in the code and now it is following the sequence... This would be the correct way to write even?

router.post('/entrega', (req, res) => {

    let pedido = new PedidoDao(req.body);

    Promise.resolve(pedido.isEntregue())
    .then(() => pedido.setEntrega())
    .then(() => responseSuccess())
    .catch( err => responseError(err))

    function responseSuccess(){
        res.json({status:true, message: 'Entrega realizada com sucesso.'});
    }

    function responseError(message){
        res.json({status:false, message: message});
    }

});
  • 1

    @Sorack made the change, added the code :D

  • Can you make an example minimum, complete and verifiable so we can help you?

  • The async/await also deals with Promise, only in a more readable way

  • @Sorack for this case, it would be more recommended to use Sync/await?

  • I believe the code is cleaner and readable, but there goes how you are structuring your application

1 answer

2


The problem is that you are only running the function without returning the promise of the subsequent function. Then you can change your code to:

// ...
Promise.resolve(pedido.isEntregue())
  .then(function() { return pedido.setEntrega(); })
  .then(function() { return responseSuccess(); })
  .catch(err => responseError(err));
// ...

Or:

// ...
Promise.resolve(pedido.isEntregue())
  .then(pedido.setEntrega)
  .then(responseSuccess)
  .catch(err => responseError(err));
// ...

In this way you inform the chain what promise it must await.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.