The suggested array urls = ['1.txt', '2.txt', '3.txt']
does not make much
sense to me, so I will instead use:
urls = ['https://jsonplaceholder.typicode.com/todos/2',
'https://jsonplaceholder.typicode.com/todos/3']
The JSONs of the two URLs:
{"userId":1,"id":2,"title":"quis ut nam facilis et officia qui",
"completed":false}
{"userId":1,"id":3,"title":"fugiat veniam minus","completed":false}
The goal is to get an array of objects, where each object contains the title
value from the corresponding URL.
To make it a little more interesting, I will assume that there is already an
array of names that I want the array of URL results (the titles) to be
merged with:
namesonly = ['two', 'three']
The desired output is an array of objects:
[{"name":"two","loremipsum":"quis ut nam facilis et officia qui"},
{"name":"three","loremipsum":"fugiat veniam minus"}]
where I have changed the attribute name title
to loremipsum
.
const namesonly = ['two', 'three'];
const urls = ['https://jsonplaceholder.typicode.com/todos/2',
'https://jsonplaceholder.typicode.com/todos/3'];
Promise.all(urls.map(url => fetch(url)
.then(response => response.json())
.then(responseBody => responseBody.title)))
.then(titles => {
const names = namesonly.map(value => ({ name: value }));
console.log('names: ' + JSON.stringify(names));
const fakeLatins = titles.map(value => ({ loremipsum: value }));
console.log('fakeLatins:\n' + JSON.stringify(fakeLatins));
const result =
names.map((item, i) => Object.assign({}, item, fakeLatins[i]));
console.log('result:\n' + JSON.stringify(result));
})
.catch(err => {
console.error('Failed to fetch one or more of these URLs:');
console.log(urls);
console.error(err);
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
Reference
.then
on the return value of.forEach(…)
, or rather on….text()
?texts
and observe it to be still empty?