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
You have to return the fetch too. The return you're putting inside the then block returns to the fetch and not getPurchaseOrderInfo.
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.