1

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

abendevs
  • 136
  • 1
  • 11
  • you're not returning anything. (return the fetch) – pilchard Dec 05 '21 at 00:43
  • 2
    The `undefined` comes from `console.log(getPurchaseOrderInfo());` because that function doesn’t return anything. The `console.log(msg);` clearly logs the object below. `return msg.status ? msg.data : false;` doesn’t return anywhere; you discard that promise chain. Did you expect this `return` statement to somehow cross the function boundary of `(msg) => {`…`}`? Please see [How to return the response from an asynchronous call](/q/14220321/4642212). – Sebastian Simon Dec 05 '21 at 00:43
  • can you explain me why? – abendevs Dec 05 '21 at 00:44
  • 1
    Because functions without explicit returns always return undefined. – pilchard Dec 05 '21 at 00:45
  • `return fetch(URL_ROOT ...` keep in mind it will return a Promise, you'll need to `getPurchaseOrderInfo().then(res => console.log(res));` Once in async land always in async land. (no wardrobes...) – pilchard Dec 05 '21 at 00:47

2 Answers2

0

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

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.

owenizedd
  • 1,187
  • 8
  • 17