」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用 Promise.all 從 URL 陣列中取得和解析文字資料?

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

發佈於2024-11-14
瀏覽:744

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

使用Promise.all 取得URL 陣列

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

假設您有一個URL 字串陣列:
var urls = ['1.txt', '2.txt', '3.txt']; // Text files containing "one", "two", "three"
var urls = ['1.txt', '2.txt', ' 3 。 TXT']; // 包含「一」、「二」、「三」的文字檔案

期望輸出為文字內容陣列:
var urls = ['1.txt', '2.txt', '3.txt']; // Text files containing "one", "two", "three"
var text = ['one' , '二', '三'];

使用Promise.all 允許您連結多個非同步操作。在這種情況下,它可用於首先獲取每個 URL,然後從每個回應中提取文字:
var urls = ['1.txt', '2.txt', '3.txt']; // Text files containing "one", "two", "three"
Promise.all(urls.map(url => fetch(url))) .then(響應=> Promise.all(responses.map(res => res.text())) ) .then(文本=> { // ... });

在上面的程式碼中,Promise.all 使用了兩次:一次用於發起所有 URL 的抓取,第二次用於從每個回應中獲取文字內容。

An另一種方法是將兩個操作組合到一個 Promise.all 鏈中,可以實現如下:
var urls = ['1.txt', '2.txt', '3.txt']; // Text files containing "one", "two", "three"
Promise.all(urls.map(url => 取得(網址) .then(resp => resp.text()) )) .then(文本=> { // ... });

此外,您可以使用 async/await 進一步簡化此程式碼:
var urls = ['1.txt', '2.txt', '3.txt']; // Text files containing "one", "two", "three"
const texts = wait Promise.all(urls.map(async url => { const resp = 等待 fetch(url); 返回 resp.text(); }));

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

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3