我想将字符串数组传递给Cloudflare工作者,然后让它遍历这些字符串并为每个字符串进行一次GET,然后将JSON添加到get返回的列表中,该列表由该工作者返回给来电者。
一些伪代码:
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
我知道如何根据此SO帖子提出非阻止请求。我无法解决的是:
答案 0 :(得分:2)
您可以使用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
}
答案 1 :(得分:1)
Promise.all
是可行的方法,甚至在文档中也有一个易于理解的示例,说明了如何在Workers中使用它:https://developers.cloudflare.com/workers/recipes/aggregating-multiple-requests/
如果任何请求失败,awaiting
上的Promise.all
都会抛出,因此如果需要,可以用try/catch
包装。