Skip to content

Add an Example using event.waitUntil() for caching a request #72

Open

Description

@GregBrimble

It let's you respond rapidly, and then save data, which can be used to speed up subsequent requests.

https://developers.cloudflare.com/workers/about/tips/fetch-event-lifecycle/

let url = 'https://ca88e957.ngrok.io/log'

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event))
  event.waitUntil(postLog(JSON.stringify({hello: 'hi'})))
})

function postLog(data) {
  return fetch(url, {
    method: 'POST',
    body: data,
  })
}

/**
 * Respond to the request
 * @param {Request} request
 */
async function handleRequest(event) {
  url = 'https://ca88e957.ngrok.io/magic'
  return new Response('hello world', {status: 200})
}

https://ca88e957.ngrok.io/magic is fetched after the repsonse is sent back.

Activity

  1. added
    documentation
    enhancement
    on May 8, 2020
  2. self-assigned this
    on May 8, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

documentationenhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions