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});
}
});
@Sorack made the change, added the code :D
– Pedro Daher
Can you make an example minimum, complete and verifiable so we can help you?
– Sorack
The
async/await
also deals withPromise
, only in a more readable way– Sorack
@Sorack for this case, it would be more recommended to use Sync/await?
– Pedro Daher
I believe the code is cleaner and readable, but there goes how you are structuring your application
– Sorack