'Returning an updated array after for loop has finished
I have an async function that calls one API end point to pull the sales orders for the day, retrieves the sales orders info and pushes each sales order object to an array (salesOrders); then I for loop through each sales order in the array, call another API endpoint to retrieve the line items for each sales order, and then appends each line item to the lineItem array inside of said sales order object.
I'm posting the last half of the function since the first half of the function where it retrieves the sales orders and formats them works.
Clearly my function is returning my salesOrders array before the forEach loop has had a chance to finish retrieiving, formatting, and appending the line items to each sales order object's lineItem array. How do I return the salesOrders array where each sales order object has an updated lineItems array?
//SEARCH THROUGH EACH SALES ORDER TO FIND LINE ITEMS
salesOrders.forEach(order => {
let filterPrefix = "?filter=SalesOrderRecordID eq ";
let formattedURL = baseURL + salesOrderLine + filterPrefix + order.RecordID;
formattedURL.toString();
axios.get(formattedURL, options).then(res => {
let data = res.data.value
data.forEach(item =>{
//CREATE A LINE ITEM WITH MORE INFO THAN NEEDED FOR KATANA, MAY NEED TO CREATE A NEW PRODUCT IF ONE NOT FOUND
let lineItem = {
customer_id: order.KatanaCustomerID, //katana customer id
recordID: item.Item_RecordID, //record number in method, not necessary in Katana
SalesOrderRecordID: order.RecordID, //actual sales order record id in method, not necessary in Katana
order_no: order.RefNumber, //sales order number
variant_id: '', //variant id --> the ID in Katana, blank for now
name: item.Desc, //item description in method will be item name in katana
quantity: item.Quantity,
price_per_unit: item.Rate, //price per unit
category_name: item.ItemType, //Category in katana
//IF we have to create a new product, variants object is required for Katana
is_producible: true,
is_purchasible: true,
variants: {
sku: item.Item, //the SKU in method, it could be a product OR material in Katana
purchase_price: 0,
sales_price: item.Rate,
config_attributes: {
config_name: 'standard',
config_value: 'default'
}
}
}
//console.log(lineItem)
order.LineItems.push(lineItem)
})
})
.then(result => {
console.log(salesOrders) // stockoverflow friends -- the salesOrder object in this step includes all of the properly formatted line items in the lineItems array
return salesOrders; //obviously pointless, not returning anything to any variable
})
.catch(err => {
console.log(err)
})
})
console.log(salesOrders) //the line items array is empty, obviously returning salesOrders before the for loop has had a chance to populate each line item array
return salesOrders }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
