首頁  >  文章  >  web前端  >  如何使用 Promise.all 從 URL 陣列中取得和解析文字資料?

如何使用 Promise.all 從 URL 陣列中取得和解析文字資料?

Susan Sarandon
Susan Sarandon原創
2024-10-26 16:16:30721瀏覽

How to Fetch and Parse Text Data from an Array of URLs with Promise.all?

使用Promise.all 取得URL 陣列

利用Promise.all 從一組URL 擷取文字資料陣列是一種合適的方法。以下是有效完成此任務的方法:

假設您有URL 字串陣列:

<code class="js">var urls = ['1.txt', '2.txt', '3.txt']; // Text files containing "one", "two", "three"</code>

所需的輸出為文字內容陣列:

<code class="js">var text = ['one', 'two', 'three'];</code>

使用Promise.all 允許您連結多個非同步操作。在這種情況下,它可用於首先獲取每個URL,然後從每個回應中提取文字:

<code class="js">Promise.all(urls.map(url => fetch(url)))
  .then(responses =>
    Promise.all(responses.map(res => res.text()))
  )
  .then(texts => {
    // ...
  });</code>

在上面的程式碼中,Promise.all 使用了兩次:一次用於啟動所有回應的取得URL,並再次從每個回應中取得文字內容。

另一種方法,將這兩個操作組合到一個Promise.all 鏈中,可以實現如下:

<code class="js">Promise.all(urls.map(url =>
  fetch(url)
    .then(resp => resp.text())
))
.then(texts => {
  // ...
});</code>

此外,您可以使用async/await 進一步簡化此程式碼:

<code class="js">const texts = await Promise.all(urls.map(async url => {
  const resp = await fetch(url);
  return resp.text();
}));</code>

這兩種方法都有效地利用Promise.all 來實現獲取URL 數組並提取關聯文本內容的預期結果。

以上是如何使用 Promise.all 從 URL 陣列中取得和解析文字資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn