H
Hono4mo ago
tombyrer

return early from Promise loop

Platform: Clouldflare Workers & KV So I have a form where that I use to search in my KV storage & return matches. Seems the standard that Hono uses is a Promise.all() & .map inside that. But after I got all the matches I want, it still loops the Promises/map. How do I stop the Promise/map loop, & return the matches?
app.post( '/searching',
csrf(),
async (c) => {
const { keys } = await c.env[KVq].list()
const allKV = await Promise.all(
//loop though results in KV storage to see if they match user input
keys.map( async ({ name }, index)=>{ // `name` is key
const valueStr = await c.env[KVq].get(name)
//... see if matches, add to accumulator, then return accumulator
app.post( '/searching',
csrf(),
async (c) => {
const { keys } = await c.env[KVq].list()
const allKV = await Promise.all(
//loop though results in KV storage to see if they match user input
keys.map( async ({ name }, index)=>{ // `name` is key
const valueStr = await c.env[KVq].get(name)
//... see if matches, add to accumulator, then return accumulator
(Might be more a general JS question, sorry. But is for my Hono/CF project. TIA)
2 Replies
Aditya Mathur
Aditya Mathur4mo ago
Okay, just to get the idea you are trying to loop through all the keys in async and want to find the key which matches first, resolve it and discard all the remaining promises? And there can be some promises which were resolved before finding the match also, right?
tombyrer
tombyrerOP4mo ago
Yes, but there can be more than 1 key. But they should only match 1:1, so if 3 keys are being looked up, then there should be at max only 3 results. So once that third result is found, the loop should stop.
Want results from more Discord servers?
Add your server