Closed jrf0110 closed 1 year ago
Currently, the aggregate requests example requests each body in series:
const btc = await btcResp.json() const eth = await ethResp.json() const ltc = await ltcResp.json()
This should be done all at once
Proposal 1
This would be a pretty minimal change:
const [btc, eth, ltc] = await Promise.all([btcResp, ethResp, ltcResp].map(res => res.json()))
Proposal 2
I kinda just went all out
// Make multiple requests, aggregate the responses and // send it back as a single response. const currencies = ['BTC', 'ETH', 'LTC'] addEventListener('fetch', event => { event.respondWith(fetchAndLog(event.request)) }) async function fetchAndLog(request) { const [btc, eth, ltc] = await Promise.all( currencies .map(currency => fetch(`https://api.coinbase.com/v2/prices/${currency}-USD/spot`)) .map(p => p.then(res => res.json())) .map(p => p.then(({ data: { amount } }) => amount)) ) const body = { btc, eth, ltc } return new Response(JSON.stringify(body, null, 2), { status: 200, headers: {'Content-Type': 'application/json'} }) }
Hello @jrf0110! This is very due for a response. Thanks for the recommendation to simplify the code. Closing this issue because this code has been updated.
Currently, the aggregate requests example requests each body in series:
This should be done all at once
Proposal 1
This would be a pretty minimal change:
Proposal 2
I kinda just went all out