I am struggling with my async/await setup in an API route where I need to merge data from two sources into one object before returning it. The problem arises when I try to push data into a second array within the .then()
block, as the array named clone
ends up empty ([]
). How can I effectively handle making an api request, merging data, and returning the result?
The code snippet for fetching:
export default async function getProduct(product_id) {
const product = await fetch(
`${process.env.PRIVATE_APP_URL}/products/${product_id}.json`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
},
}
).then((result) => {
return result.json();
});
return product.product;
}
Snippet from the API handler:
const recharge_subscription_res = await rechargeAPI(
"GET",
`https://api.rechargeapps.com/subscriptions?customer_id=${recharge_customer.id}`
);
const closest_array = recharge_subscription_res.subscriptions.filter(
(e) => e.next_charge_scheduled_at == closest_date
);
let clone = [];
closest_array.forEach((element) => {
getProduct(element.shopify_product_id).then((product) => {
element.shopify_product_handle = product.handle;
element.shopify_product_image_url = product.image.src;
clone.push(element);
});
});
console.log(clone);
The issue is that clone
should log an array of objects like closest_array
, but instead logs as an empty array. My situation is unique in that it involves an Express.js API rather than just front end tasks. Any help or insights would be greatly appreciated.