首頁 > web前端 > js教程 > 主體

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

Susan Sarandon
發布: 2024-10-26 16:16:30
原創
719 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!