In EdgeRoutine (ER), each request has a lifecycle. This topic describes the lifecycle of an ER request.
Introduction to request lifecycle
In a fetch event, the request context closes only after the Response object is completely
returned to
event.respondWith
and the CDN gateway.
Note After a context closes, all pending subrequests are canceled. ER attempts to recycle
all allocated resources but does not destroy the JavaScript virtual machine.
Examples
In the following sample code, the first fetch request may not have been executed and
ER has returned the hello world message to the CDN gateway. In this case, all pending
fetch requests are canceled and you cannot determine whether all the fetch requests
have been executed.
addEventListener('fetch', (event) => {
event.respondWith(handle(event));
});
async function handle(event) {
// 1. Initiate a fetch request asynchronously. This request does not use the await keyword. Therefore, the request runs in parallel with the JavaScript code.
fetch("http://www.aliyun.com/data", {body: "this is my log", method: "POST"});
// 2. Initiate a response immediately. The fetch request may not have been executed when the hello world message is
// returned to the client.
return "hello world";
}
To ensure that a specific Promise object will be executed or time out, you can call
the
event.waitUntil
function. event.waitUntil
ensures that the asynchronous fetch request initiated by the context of a specific
request is executed after the Response object is returned. Sample code:addEventListener('fetch', (event) => {
event.respondWith(handle(event));
});
async function handle(event) {
// 1. Initiate a fetch request asynchronously. This request does not use the await keyword. Instead, it uses event.waitUntil to ensure that
// the fetch request is executed after the Response object is returned, or after the context of the request times out.
event.waitUntil(
fetch("http://www.aliyun.com/data", {body: "this is my log", method: "POST"}));
// 2. Initiate a response immediately. The preceding fetch request will be executed when the hello world message is returned to the client,
// even if a response is returned to the request.
return "hello world";
}
In the preceding example,
event.waitUntil
is used to ensure that the fetch request is executed. You can call waitUntil
multiple times to wait for multiple Promise objects to be executed. If one of the
Promise objects waiting in the queue throws an exception, other Promise objects may
not be executed.
Notice
waitUntil
cannot violate the rules of resources. If a resource is used against the rules, the
request is terminated.