在 cloudflare worker 中发出一堆异步子请求,并在它们全部完成后 return?

Make a bunch of async subrequests in a cloudflare worker and return once they are all complete?

我想将一个字符串数组传递给 Cloudflare worker,然后让它循环遍历这些字符串并为每个字符串执行 GET,然后添加 JSON get returns到一个列表,该列表由工作人员 return 发送给调用者。

一些伪代码:

var listOfAjaxResults
foreach someString in arrayOfStrings
{
    //Do AJAX call using someString and add to listOfResults
}

//Wait here until all requests in the loop have completed
//Return response form worker
return listOfAjaxResults

我知道如何根据此 post 发出非阻塞请求。我无法解决的是:

  1. 如何只return一旦循环中的所有请求都完成
  2. 使用什么样的线程安全数据结构,以便在每个请求完成时可以安全地将其结果添加到列表中。

您可以使用 Promise.all,re-using 您的示例:

async function example() {
    let arrayOfStrings = ["a", "b", "c"]

    let promises = []
    for (let str of arrayOfStrings) {
        // a single fetch request, returns a promise
        // NOTE that we don't await!
        let promise = fetch(str)

        promises.push(promise)
    }

    let results = await Promise.all(promises)
    // results is now an array of fetch results for the requests,
    // in the order the promises were provided
    // [fetchResult_a, fetchResult_b, fetchResult_b]

    return results
}

Promise.all is way to go, there's even easy to digest example in docs how to use it in Workers: https://developers.cloudflare.com/workers/recipes/aggregating-multiple-requests/

如果 awaiting 上的任何请求失败,Promise.all 将抛出异常,因此如果需要,最好将 try/catch 包裹起来。