The*_*dge 1 javascript cloudflare-workers
我想将一组字符串传递给 Cloudflare 工作线程,然后让它循环遍历这些字符串并对每个字符串执行 GET,然后将 get 返回的 JSON 添加到工作线程返回给调用者的列表中。
一些伪代码:
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
Run Code Online (Sandbox Code Playgroud)
我知道如何根据这篇文章提出非阻塞请求。我无法解决的是:
小智 5
您可以使用Promise.all,重新使用您的示例:
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
}
Run Code Online (Sandbox Code Playgroud)