【问题标题】:JavaScript fetch() - mapping array of ReadableStreams to arrayJavaScript fetch() - 将 ReadableStreams 数组映射到数组
【发布时间】:2018-06-02 19:21:12
【问题描述】:

我有一批从fetch() 调用返回的 Promise 数组:

const fetchResults = [Promise, Promise, Promise]

每个Promise.bodyReadableStream,将其转换为字符串似乎是一个烦人的冗长异步操作。我正在尝试使用 await 来读取正文字符串并将其映射回数组:

profileHTMLDocs.map(async (doc) => { 
    doc.text()
        .then(async (html) => { return await html; }) 
})

我已经尝试了一些变体,但它似乎仍然返回一个承诺数组而不是 html 字符串数组。我错过了什么?是不是因为隐式返回是doc.text()

【问题讨论】:

  • 那......不是应该如何使用async/await。你想await一个被标记为async的函数。

标签: javascript ecmascript-6 async-await es6-promise


【解决方案1】:

您可能想使用 Promise.all 将 Promise 数组转换为解析为字符串数组的 Promise:

const result = Promise.all(fetchResults.map(p => p.then(res => res.text())));

【讨论】:

  • 在这段代码中,result 将是一个 Promise。如果您只想要结果的值,可以使用 const result = await Promise.all(...);
  • 我不知道为什么我没有想到。
猜你喜欢
  • 2020-11-09
  • 1970-01-01
  • 2020-01-18
  • 1970-01-01
  • 2021-04-18
  • 2020-12-10
  • 1970-01-01
  • 2011-11-20
  • 1970-01-01
相关资源
最近更新 更多