A
A
andriyorehov2020-07-28 18:07:15
JavaScript
andriyorehov, 2020-07-28 18:07:15

How to return json and url from Promise.all?

Code example: https://jsfiddle.net/kza92th7/

const fetchData = () => {
  const urls = [
    "https://jsonplaceholder.typicode.com/posts/1",
    "https://jsonplaceholder.typicode.com/posts/2",
    "https://jsonplaceholder.typicode.com/posts/3",
    "https://jsonplaceholder.typicode.com/posts/4",
    "https://jsonplaceholder.typicode.com/posts/5",
    "https://jsonplaceholder.typicode.com/posts/6",
    "https://jsonplaceholder.typicode.com/posts/7",
    "https://jsonplaceholder.typicode.com/posts/8"
  ];

  const allRequests = urls.map(url => 
    fetch(url).then(response => response.json())
  );

  return Promise.all(allRequests);
};

fetchData().then(r => console.log(r));


Must be returned along with query result URL
Expected result:
[{
"url": " https://jsonplaceholder.typicode.com/posts/1 ",
"json": {
"body": "quia et susc...",
"id": 1,
"title": "sunt aut facere repellat provid...",
"userId": 1
}
}, ... ]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
andriyorehov, 2020-07-28
@andriyorehov

const fetchData = () => {
  const urls = [
    "https://jsonplaceholder.typicode.com/posts/1",
    "https://jsonplaceholder.typicode.com/posts/2",
    "https://jsonplaceholder.typicode.com/posts/3",
    "https://jsonplaceholder.typicode.com/posts/4",
    "https://jsonplaceholder.typicode.com/posts/5",
    "https://jsonplaceholder.typicode.com/posts/6",
    "https://jsonplaceholder.typicode.com/posts/7",
    "https://jsonplaceholder.typicode.com/posts/8"
  ];

  const allRequests = urls.map(url => 
  fetch(url).then( response => response.json() ).then( json => ( {url, json } ) )
);

  return Promise.all(allRequests);
};

fetchData().then(r => console.log(r));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question