JavaScript中Map函数多API请求与Object.assign合并返回值失败求助
Merging Multiple API Responses with
map() and Object.assign() in JavaScript Got it, let's walk through how to merge your purchase order data with the corresponding listing details step by step. The key here is handling asynchronous API calls properly and combining the data cleanly.
Step-by-Step Implementation
First, we'll use async/await to manage the async requests (this avoids callback hell and makes the code easier to read), Promise.all to fetch all listing data in parallel (faster than sequential requests), and Object.assign() (or the spread operator) to merge each purchase item with its listing data.
Here's the full code example:
async function mergePurchaseOrderData() { // 1. Fetch the initial purchase order data try { const poResponse = await fetch('https://gateway.trybindo.com/v2/stores/382/purchase_orders/17157'); const poData = await poResponse.json(); const purchaseItems = poData.purchase_order.purchase_items; // 2. Create an array of promises to fetch each listing const listingFetchPromises = purchaseItems.map(async (item) => { // Fetch listing using the item's source_id const listingResponse = await fetch(`https://trybindo.com/api/v2/stores/382/listings/${item.source_id}`); const listingData = await listingResponse.json(); // Merge the purchase item with its listing data // Using Object.assign: creates a new object, copies item properties, then adds listing return Object.assign({}, item, { listing: listingData.listing }); // Alternatively, use the spread operator for more readable syntax: // return { ...item, listing: listingData.listing }; }); // 3. Wait for all listing requests to finish and get merged items const mergedPurchaseItems = await Promise.all(listingFetchPromises); // 4. Reconstruct the full purchase order with merged items const mergedPurchaseOrder = { purchase_order: { ...poData.purchase_order, purchase_items: mergedPurchaseItems } }; console.log('Merged Result:', mergedPurchaseOrder); return mergedPurchaseOrder; } catch (error) { console.error('Error merging data:', error); // Handle errors (e.g., network issues, invalid responses) here } } // Run the function mergePurchaseOrderData();
Key Notes:
- Async/Await: This lets us write asynchronous code that reads like synchronous code, making it easier to follow the flow of requests.
- Promise.all: Instead of fetching listings one after another, we run all requests in parallel. This is much faster, especially if you have multiple items.
- Object.assign(): We use it to create a new object (so we don't modify the original
itemdata) that combines the purchase item properties with the listing data. The spread operator (...item) is a modern alternative that's often more readable. - Error Handling: The
try/catchblock ensures we catch any network errors or invalid API responses, so you can debug or handle failures gracefully.
Example Merged Output
For your sample data, the merged result would look like this:
{ purchase_order: { purchase_items: [ { id: 01, source_id: 24308265, listing: { base_unit: { unit_group_id: 345 } } }, { id: 02, source_id: 3820202, listing: { /* corresponding listing data */ } } ] } }
内容的提问来源于stack exchange,提问作者user6080689
相关产品推荐
相关产品推荐

