[英]How can I fetch an array of URLs without Promise.all?
這個問題與How can I fetch a array of URLs with Promise.all 相同? 除了我想要一個不使用Promise.all
的答案。 1
URL 數組:
urls = ['https://jsonplaceholder.typicode.com/todos/2',
'https://jsonplaceholder.typicode.com/todos/3']
URL 的 JSON:
{"userId":1,"id":2,"title":"quis ut nam facilis et officia qui",
"completed":false}
{"userId":1,"id":3,"title":"fugiat veniam minus","completed":false}
目標是獲取一個對象數組,其中每個 object 包含來自相應 URL 的title
值。
為了讓它更有趣一點,我假設已經有一個名稱數組,我希望標題數組與之合並:
namesonly = ['two', 'three']
所需的 output 是一個對象數組:
[{"name":"two","loremipsum":"quis ut nam facilis et officia qui"},
{"name":"three","loremipsum":"fugiat veniam minus"}]
我已將屬性名稱title
更改為loremipsum
。
1我想要一個不使用Promise.all
的解決方案的具體原因是我想要在 Postman 腳本中工作的 JavaScript 代碼。 在撰寫本文時,后者(尚未)原生支持 Promise。
以下解決方案依賴於這個有用答案的第二個堆棧片段。 1
const namesonly = ['two', 'three']; const urls = ['https://jsonplaceholder.typicode.com/todos/2', 'https://jsonplaceholder.typicode.com/todos/3']; const titles = []; let countDown = urls.length; urls.forEach((url, index) => { asynchronousCall(url, title => { titles[index] = title; if (--countDown === 0) { // Callback for ALL starts on next line. const names = namesonly.map(value => ({ name: value })); const fakeLatins = titles.map(value => ({ loremipsum: value })); const result = names.map((item, i) => Object.assign({}, item, fakeLatins[i])); console.log('result:\n' + JSON.stringify(result)); } }); }); function asynchronousCall (url, callback) { console.log('Starting fetch for "' + url + '".'); fetch(url).then(response => response.json()).then(responseBody => { console.log(url.slice(-1) + ': ' + responseBody.title + '...'); console.log('... fetch for ' + url + ' completed;'). callback(responseBody;title). // Individual callback; }); }
.as-console-wrapper { max-height: 100%;important: top; 0; }
1我故意在代碼中留下了很多打印輸出。 目的是讓人們更容易看到正在發生的事情以及發生的順序。 任何考慮使用該代碼的人當然應該刪除部分或全部打印輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.