How to force error in the return of a Promise inside another Promise

Asked

Viewed 93 times

-1

  const Firebird = require('node-firebird');
const { database } = require("../backend.conf");

async function pesqcdcidade(cidade) {

    return new Promise((resolve, reject) => {

        Firebird.attach(database, async function (err, db) {
            if (err) {
                reject(err);
            }

            const SQL = ' SELECT FIRST 1 CDCIDADE' +
                ' FROM CIDADES' +
                ' WHERE DESCRICAO =?';

            db.query(SQL, [cidade], async (err, resultParam) => {
                if (err) {
                    reject(err);
                };

                if (resultParam != undefined) {
                    if (resultParam.length > 0) {
                        for (k = 0; k < resultParam.length; k++) {
                            resolve(resultParam[k]);
                        }
                    } else {

                        resolve("inexistente")
                    }
                } else {

                    resolve("inexistente")

                }

                db.detach();
            });
        });

    });


};
async function insertCidade(endereco) {
    return new Promise((resolve, reject) => {

        Firebird.attach(database, function (err, db) {
            if (err) {
                reject(err);
            }

            const SQL = ' INSERT INTO CIDADES (CDCIDADE, DESCRICAO, CDESTADO) ' +
                ' VALUES ((SELECT COALESCE(MAX(CDCIDADE), 0) + 1 ' +
                ' FROM CIDADES), ?, ?)';

            db.transaction(Firebird.ISOLATION_READ_COMMITED, function (err, transaction) {
                if (err) {
                    reject(err);
                }

                transaction.query(SQL, [endereco.cidade, endereco.uf], function (err) {
                    if (err) {
                        reject(err);
                    }

                    transaction.commit(function (err) {
                        if (err) {
                            transaction.rollback();
                            reject(err);

                        } else {
                            resolve("OK")
                            db.detach();
                        }
                    });
                });
            })
        });
    });
};
module.exports = app => {

    const insert = async (req, res) => {

        let strTesteDescri = "cidade exemplo";
        let cdcidade = 0;

        let cliente = {
            "endereco": {
                "cidade": "exemplo de cidade",
                "uf": "RS"
            }
        }


        try {
            await pesqcdcidade(strTesteDescri)
                .then(async (resultado) => {
                    if (resultado == 'inexistente') {
                        return await insertCidade(cliente.endereco)
                            .then(
                                await pesqcdcidade(strTesteDescri)
                                    .then(resultado => {
                                        if (resultado != 'inexistente') {
                                            cdcidade = resultado.CDCIDADE
                                        }

                                    })

                            )
                            .catch((err) => {
                                throw new Error('insertCidade failed');
                            })
                    } else {
                        cdcidade = resultado.CDCIDADE
                    }
                })

        } catch (eer) {
            return res.status(500).send(err);
        }
    }

}`insira o código aqui`

1 answer

2

Two options:

  • withdraw that catch
  • return a new error within the catch.

The async/await API is very practical but creates difficulties with error management.

async function teste() {
  const res = await Promise
    .resolve(foo())
    .catch(err => {
      console.log('Erro interno', err);
      throw new Error('Erro 2');
    });
  return res;
}

function foo() {
  return Promise.reject('Erro 1');
}

teste().catch(err => console.log('Catch exterior', err.message));

Usa throw new Error(...frase...) to create a new error and so it propagates to the code that invoked that line.

  • I’m sorry but I don’t quite understand, I’m new to js, These functions that are await connect in Firebird and so need to be executed in sequence and one depends on the result of the other...

  • @Ezequielmenegás puts it throw new Error('insertCidade failed'); where you have //ERRO GERADO AQUIII

  • Worse I tried it but it didn’t fall in the outside catch

  • @Ezequielmenegás you have to give return in await insertCidade. The truth is that this code has other problems besides the catch we discussed here. It gives a return, more than that I need to see more code to understand and correct some things in your asynchronous chaining

  • I put the whole procedure but it’s not working, my structure is half confused by having no experience

Browser other questions tagged

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