使用Promise.all 征服多個URL 獲取
在異步編程領域,Promises 提供了強大的機制來處理諸如獲取之類的非同步任務來自多個URL 的資料。正如您所遇到的,嘗試將此用例融入 Promise.all 範例可能是一個絆腳石。
讓我們剖析一下您嘗試的解決方案:
var promises = urls.map(url => fetch(url)); var texts = []; Promise.all(promises) .then(results => { results.forEach(result => result.text()).then(t => texts.push(t)) })
此方法存在以下問題:關鍵缺陷:forEach 既不返回數組也不返回Promise,使您處於Promise-void狀態,無法存取獲取的文字。
為了糾正這個問題,必須使用Promise.all 兩次,一次是為了獲取URL 並一次從響應中提取文本:
Promise.all(urls.map(u=>fetch(u))).then(responses => Promise.all(responses.map(res => res.text())) ).then(texts => { … })
或者,您可以通過將獲取和文本檢索合併為一個步驟來簡化該過程:
Promise.all(urls.map(url => fetch(url).then(resp => resp.text()) )).then(texts => { … })
了解更多簡潔的解決方案,擁抱async/await 的強大功能:
const texts = await Promise.all(urls.map(async url => { const resp = await fetch(url); return resp.text(); }));
這些方法使您能夠高效處理多個URL 獲取,使您能夠建立包含提取文字的所需物件。
以上是如何使用 Promise.all 有效率地從多個 URL 取得資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!