Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
GregBrimble opened this issue May 8, 2020 · 0 comments
Open

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

GregBrimble opened this issue May 8, 2020 · 0 comments
Assignees
Labels
documentation Improvements or additions to documentation enhancement New feature or request

Comments

@GregBrimble
Copy link
Member

GregBrimble commented May 8, 2020

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.

@GregBrimble GregBrimble added documentation Improvements or additions to documentation enhancement New feature or request labels May 8, 2020
@GregBrimble GregBrimble self-assigned this May 8, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant