Search code examples
javascriptpromisefetch-api

how to use Promise.all method?


I'm having problems using Promise.all When I try to loop through the array to turn the elements into json it does not work, can someone explain me why It does not work?

function getData() {

let getUsers = fetch('https://jsonplaceholder.typicode.com/users')
let getTodos = fetch('https://jsonplaceholder.typicode.com/todos')
Promise.all([getUsers, getTodos])
   .then(data => {
          data.forEach(item => {
            item.json()
            console.log(item)});
   })
   .catch(err => console.log(err))
}; 
getData();

Solution

  • Promise.all() takes an array of Promises and returns a Promise that resolves to an array of values returned by promises.

    For example:

    const promiseA = Promise.resolve('valueA');
    const promiseB = Promise.resolve('valueB');
    
    Promise.all([promiseA, promiseB]).then(data => {
       console.log(data); // [ 'valueA', 'valueB' ]
    })
    

    So data is an array [ users, todos ] (where users is result of fetch('https://jsonplaceholder.typicode.com/users'))

    function getData() {
    
    let getUsers = fetch('https://jsonplaceholder.typicode.com/users').then(response => response.json())
    let getTodos = fetch('https://jsonplaceholder.typicode.com/todos').then(response => response.json())
    
    Promise.all([getUsers, getTodos])
       .then(data => {
             const [users, todos] = data;
              users.forEach(user => {
                console.log(user)
              });
              todos.(todo => {
                console.log(todo)
              });
       })
       .catch(err => console.log(err))
    }; 
    getData();