addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));

async function handleRequest(_event) {
  const pending_reqs = [
    // This endpoint returns "Cat" in the response body
    fetch("https://http-me.fastly.dev/body=cat", { backend: "origin_0" }),
    // This endpoint returns "Dog" in the response body
    fetch("https://http-me.fastly.dev/body=dog", { backend: "origin_1" }),
  ];

  // Send two asynchronous backend requests and store the responses in the array once they are received.
  const logs = [];
  const responses = [];
  await Promise.all(
    pending_reqs.map(async (req, idx) => {
      logs.push('REQ' + idx);
      const r = await req;
      const t = await r.text();
      logs.push('RESP' + idx);
      responses.push(t);
    })
  );
  console.log(logs.join(' '));

  // Create a new response from the two origin responses.
  return new Response(`${responses[0]} responded first, ${responses[1]} responded next`, {
    status: 200,
  });
}