How to wait for the return of a function with async-await? (asynchronism - javascript)

1

I have 2 functions, the 1st one is an async function that calls the second one. This 2nd is called consult_clubRN. The problem is that I am using async and await to wait for the results of the 2nd function but it seems that when invoking the function consult_clubRN the execution continues, I mean, it does not wait for this function to finish its execution. It can be abstracted from the rest of the code. What I want to achieve is that on line 17 when calling the function consultar_clubRN wait for the results

async function (req, res) {
    let club_rn_ok = {"estado": true};
    let id_yoCorro = 2;
    let codigoProducto = req.body.codigo_producto;
    let codigo_rn = req.body.codigo_rn;
    let dni_comprador = req.body.documento;
    if (codigo_rn !== '') {
      club_rn_ok = await consultar_clubRN(dni_comprador, codigo_rn, id_yoCorro)
        .catch((err)=>{
          sails.log.info(err);
          return res.json(err);
        });
    }
    Producto.findOne({codigo: codigoProducto}).populate('precio').exec((err, producto) => {
      if (err) {
        return res.json({
          detalle: 'Error al buscar el producto en la base',
          estado: false
        });
      }
      Venta.find({id_evento: id_yoCorro, estado: {'!': [9]}}).exec((err, ventas) => {
        if (err) {
          return res.json({
            detalle: 'Error al buscar ventas en la base',
            estado: false
          });
        }
        Evento.findOne({id: id_yoCorro}).exec((err, yocorro) => {
          if (err) {
            return res.json({
              detalle: 'Error al buscar el evento en la base',
              estado: false
            });
          }
          if (yocorro.stock > ventas.length) {
            if (club_rn_ok.estado) {
              let nueva_venta = {
                'estado': 1,
                'id_evento': id_yoCorro,
                'codigo_producto': codigoProducto,
                'precio_producto': producto.precio[0].precio,
                'precio_final': producto.precio[0].precio,
                'cant_entradas': producto.cantidad,
                'codigo_rn': codigo_rn,
                'titular_rn': dni_comprador,
                'documento_comprador': dni_comprador,
                'mail_comprador': req.body.email,
                'telefono_comprador': req.body.telefono,
                'domicilio_comprador': req.body.calle,
                'nombre_comprador': req.body.nombre,
              };
              Venta.create(nueva_venta).exec((err, res_venta) => {
                if (err) {
                  return res.json({
                    detalle: 'Error al crear una nueva venta en la base',
                    estado: false
                  });
                }
                let nuevo_inscripto = {
                  'id_evento': id_yoCorro,
                  'id_venta': res_venta.id,
                  'nombre': req.body.nombre,
                  'apellido': req.body.apellido,
                  'documento': dni_comprador,
                  'email': req.body.email,
                  'telefono': req.body.telefono,
                  'pais': req.body.pais,
                  'provincia': req.body.provincia,
                  'localidad': req.body.localidad,
                  'calle': req.body.calle,
                  'fecha_nacimiento': req.body.fecha_nacimiento,
                  'sexo': req.body.sexo,
                  'talle': req.body.talle
                };
                Inscripto.create(nuevo_inscripto).exec((err, res_inscripto) => {
                  if (err) {
                    return res.json({
                      detalle: 'Error al crear un nuevo  inscripto en la base',
                      estado: false
                    });
                  }
                  /* TODO: Antes de retornar se debe agregar el inscripto_contacto tambien*/
                  return res.send({estado: true, recurso: res_venta});
                });
              });
            } else {
              return res.json({
                detalle: club_rn_ok.mensaje,
                estado: false
              });
            }
          } else {
            return res.json({
              detalle: 'No hay stock disponible en yo Corro',
              estado: false
            });
          }
        });
      });
    });
  }
}

function consultar_clubRN(dni, codigo_rn, evento) {
  return new Promise((resolve, reject) => {
    Venta.findOne({codigo_rn: codigo_rn, id_evento: evento, estado: {'!': [9]}}).exec((err, venta_rn) => {
      if (err) {
        reject({
          'mensaje': 'Problemas al consultar uso de tarjeta club rio negro' + err.status,
          'estado': false
        });
      }
      if (venta_rn !== 'undefined') {
        reject({
          'mensaje': 'La tarjeta de Club Rio Negro que quiere usar ya fue utilizada',
          'estado': false
        });
      } else {
        let parseString = require('xml2js').parseString;
        const request = require("request");
        request.get({
          url: 'http://servicioX',
          qs: {'beneficiary': '{CardNumber:' + codigo_rn + ',DocumentNumber:' + dni + '}'}
        }, (err, response, body) => {
          parseString(body, {ignoreAttrs: true}, function (err, result) {
            if (result.StateResult.Code[0] === 0) {
              sails.log.info("Codigo de tarjeta valido. Aplicar descuento");
              resolve({
                'mensaje': 'Codigo de tarjeta valido. Aplicar descuento',
                'estado': true
              });
            } else {
              sails.log.info("Codigo de tarjeta no valido. NO Aplicar descuento");
              reject({
                'mensaje': 'Codigo de tarjeta no valido. NO Aplicar descuento',
                'estado': false
              });
            }
          });
        })
      }
    });
  });
}
    
asked by Lucas Pérez 09.08.2018 в 22:41
source

1 answer

0

According to the documentation: Queries sails js the asynchronism is handled correctly, the error must be within the second function called.

Check type checks also, === compare that both variables have the same types, and HTTP responses are always string.

This particular line:

if (result.StateResult.Code[0] === 0)
    
answered by 10.08.2018 / 18:07
source