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

209
Vistas
undefined value from function in javascript

I'm trying to get purchase order details from server

This is my code:

    function getPurchaseOrderInfo() {
      try {
        let po_ref = document.getElementById("po_ref").value;
        let data = new FormData();
        data.append("po_ref", po_ref);
        data.append("request_token", request_token);
        fetch(URL_ROOT + "purchase-orders/get_purchase_order_info", {
            method: "POST",
            body: data,
          })
          .then((res) => res.json())
          .then((msg) => {
            console.log(msg);
            return msg.status ? msg.data : false;
          });
      } catch (error) {
        console.log(error);
      }
    }

    console.log(getPurchaseOrderInfo());

This is what I got by executing the script

I have no idea why I'm getting an undefined value instead of object shown at console.log(msg);

I need the object to print a table and show details to user

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

0

You have to return the fetch too. The return you're putting inside the then block returns to the fetch and not getPurchaseOrderInfo.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Fetch returns a promise, hence the .then() is also a promise. If you want to use the data to outside of the function you can return the promise and use it anywhere you invoke the function.
Here’s one simple example with ES6 :


function myFunc(){
    return fetch(…).then(res => res.json())
}

function anotherFunc(){
     myFunc()
        .then(data => {
             console.log(data);
         });
}

For side note, I personally prefer ES7 async/await, it is much more simpler for me.

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