我有一组从一批 fetch()
调用返回的 Promises:
const fetchResults = [ promise , promise , promise ]
每个Promise
的.body
是ReadableStream ,将其转换为字符串似乎是一个烦人的冗长异步操作。我尝试使用await 读取正文字符串并将其映射回数组:
profileHTMLDocs.map(async (doc) => {
doc.text()
.then(async (html) => { return await html; })
})
我尝试了一些变体,但它似乎仍然返回一个 promise 数组而不是 html 字符串数组。我缺少什么?是因为隐式返回的是doc.text()
吗?
最佳答案
您可能想使用 Promise.all 将 Promise 数组转换为解析为字符串数组的 Promise:
const result = Promise.all(fetchResults.map(p => p.then(res => res.text())));
关于JavaScript fetch() - 将 ReadableStreams 数组映射到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50660377/