How can I retrieve the result of a Javascript Promise that resolves the fastest, while still allowing the other promises to continue running even after one has been resolved? See example below.
// The 3 promises in question
const fetchFromGoogle: Promise<T> = googlePromise()
const fetchFromAmazon: Promise<T> = amazonPromise()
const fetchFromCloudflare: Promise<T> = cloudflarePromise()
// Retrieve the result of the fastest resolving promise
const winner: T = Promise.race([fetchFromGoogle, fetchFromAmazon, fetchFromCloudflare])
If, for example, the fetchFromAmazon
call wins in terms of speed, its result will be returned to the client, but the other two promises will continue executing asynchronously.
This code is running within a Cloudflare Worker
, and the functionality to return the winning promise while allowing the evaluation of the others can be achieved using the waitUntil
API linked below.
I have considered two options:
- An unknown Javascript API that may handle this automatically
- Using a method like this to identify the "losing" promises and execute them with
Cloudflare Workers
' context.waitUntil function to ensure continuous evaluation despite already returning a result to the client.
I believe that utilizing Promise.all
would not meet this requirement, as it would wait for all three promises to complete before returning any result.