Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
Two requests inside a service in express

Currently I'm working in a project where I'm trying to build a service in express which calls another two external EP. I have a trouble here, because express shows me an error that I can't understand. But I suppose, the way I'm working it should be wrong. So

app.get("/items/:id", (req, res) => {
  return request.get({
    url: `https://myapi.com/${req.params.id}`,
    json: true
  },
  (error, response) => {
    if(error) {
      return res.send("Error ocurred");
    }
    const itemDesc = request.get({                        // Here I'm trying to do the second call and use it later
      url: `https://myapi.com/${req.params.id}/description`,
      json: true
    },
    (error, responseDesc) => {
      return responseDesc
    });

    const itemDetails = response.body;
    const strPrice = itemDetails.price.toString().split('.');
    const numberPrice = parseInt(strPrice[0]);
    const floatPrice = strPrice[1] ? parseInt(strPrice[1]) : 00;

    return res.send({
      id: itemDetails.id,
      title: itemDetails.title,
      price: {
        currency: itemDetails.currency_id,
        amount: numberPrice,
        decimals: floatPrice,
      },
      picture: itemDetails.pictures[0].url,
      condition: itemDetails.condition,
      free_shipping: itemDetails.shipping.free_shipping,
      sold_quantity: itemDetails.sold_quantity,
      description: itemDesc                     // Here I'm using the variable of the previous request
    });
  });
});

Basically, the error I get is that I can't do two calls. I know that because if I remove the nested request, it works. The error I get is the following: enter image description here

My question is: Is there any way to do two external request inside the same method? Thanks in advance

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

it's cleaner if you do it with async await in your case. modify your code like this

app.get("/items/:id", async(req, res) => {
  try {
    const promise1 = fetch(`https://myapi.com/${req.params.id}`).then(data => data.json())
    const promise2 = fetch(`https://myapi.com/${req.params.id}/description`)

    const [itemDetails, itemDesc] = await Promise.all([promise1, promise2])
    const strPrice = itemDetails.price.toString().split('.');
    const numberPrice = parseInt(strPrice[0]);
    const floatPrice = strPrice[1] ? parseInt(strPrice[1]) : 00;

    res.send({
      id: itemDetails.id,
      title: itemDetails.title,
      price: {
        currency: itemDetails.currency_id,
        amount: numberPrice,
        decimals: floatPrice,
      },
      picture: itemDetails.pictures[0].url,
      condition: itemDetails.condition,
      free_shipping: itemDetails.shipping.free_shipping,
      sold_quantity: itemDetails.sold_quantity,
      description: itemDesc // Here I'm using the variable of the previous request
    });

  } catch (
    res.send("Error ocurred")
  )
  
});

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda