Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
How can you add multiple sources in fetch

I'm starting and one of the first things I'm trying on my own is how to add multiple sources to this promise:

    const getTodos = async () =>{
const response = await fetch('todos/resource.json');
if(response.status !== 200){
    throw new Error('Cannot fetch data');
}
const data = await response.json();
return data;
};
getTodos()
    .then(data => console.log ('Resolved: ', data))
    .catch(err => console.log ('Rejected', err.message);

I tried making different variables and using .then after to print them but that didn't work.

    const getTodos = async () =>{
    const response = await fetch('todos/resource1.json');
    if(response.status !== 200){
        throw new Error('Cannot fetch data'); // Error from the source
    }
    const data = await response.json();
    return data;
    const response2 = await fetch('todos/resource2.json');
    if(response2.status !== 200){
        throw new Error('Cannot fetch data'); // Error from the source
    }
    const data2 = await response2.json();
    return data2;
};

getTodos()
    .then(data => console.log ('Resolved: ', data))
    .then(data2 => console.log ('Resolved: ', data2))
    .catch(err => console.log ('Rejected', err.message)) // Error for json file
    ;

any tips?

Edit1:

I'm essentially trying to translate this

const getTodos = (resource) => {

return new Promise((resolve, reject) =>{
    const request = new XMLHttpRequest();
    request.addEventListener('readystatechange', () =>{
        if(request.readyState === 4 && request.status === 200){ 
            const data = JSON.parse(request.responseText);
            resolve(data);
        } else if(request.readyState === 4){
            reject('Error getting resource');
        }
    });
    request.open('GET', resource);
    request.send();
})
}

// Then - To get data successfully, Catch - to catch error
getTodos('todos/food.json').then(data =>{
    console.log('Promise resolved', data);
    return getTodos('todos/sports.json')
}).then(data =>{
    console.log('Promise 2 resolved', data)
    return getTodos('todos/games.json')
}).then(data =>{
    console.log('Promise 3 resolved', data)
    return getTodos('todos/sportss.json') //Error example
}).then(data =>{
    console.log('Promise 4 resolved', data)
}).catch(err => {
    console.log('Promise Rejected', err)
});

into async await.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If you want to return multiple things from a function, then you either need to return an array or an object. Two return statements will not work. As soon as the first return is hit, you're done. The only difference in an async function is that your single return statement determines the resolution value of the promise. You're still limited to one return though.

So here's an example which returns an object:

const getTodos = async () =>{
    const response = await fetch('todos/resource1.json');
    if(response.status !== 200){
        throw new Error('Cannot fetch data'); // Error from the source
    }
    const data = await response.json();
    const response2 = await fetch('todos/resource2.json');
    if(response2.status !== 200){
        throw new Error('Cannot fetch data'); // Error from the source
    }
    const data2 = await response2.json();
    return {
      data1,
      data2,
    }
};

// used like:
getTodos().then(result => {
  console.log(result.data1);
  console.log(result.data2);
});

// or with async/await:
async someFunction () {
  const result = await getTodos();
  console.log(result.data1);
  console.log(result.data2);
}
about 4 years ago · Juan Pablo Isaza Report

0

From the above comment ...

"The OP might have a look into either or both Promise.all and Promise.allSettled"

async function fetchTodoItems(resourceList) {
  return Promise.all(
    resourceList
      .map(url =>
        fetch(url)
          .then(response => response.json())
      )
  );
}

(async () => {
  try {

    const todoItems = await fetchTodoItems([
      'https://jsonplaceholder.typicode.com/todos/1',
      'https://jsonplaceholder.typicode.com/todos/11',
      'https://jsonplaceholder.typicode.com/todos/21',
      'https://jsonplaceholder.typicode.com/todos/31',
      'https://jsonplaceholder.typicode.com/todos/41',
      'https://jsonplaceholder.typicode.com/todos/51',
      'https://jsonplaceholder.typicode.com/todos/61',
    ]);
    console.log({ todoItems });

  } catch(exception) {

    console.log('failed to fatch data with ...', { exception });
  }
})();
.as-console-wrapper { min-height: 100%!important; top: 0; }

Promise.all fails fast and the error/exception handling can be done at one place within the code ...

async function fetchTodoItems(resourceList) {
  return Promise.all(
    resourceList
      .map(url => new Promise((_, reject) => reject('invalid api call'))
        // fetch(url)
        //  .then(response => response.json())
      )
  );
}

(async () => {
  try {

    const todoItems = await fetchTodoItems([
      'https://jsonplaceholder.typicode.com/todos/1',
    ]);
    console.log({ todoItems });

  } catch(exception) {

    console.log('failed to fatch data with ...', { exception });
  }
})();
.as-console-wrapper { min-height: 100%!important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!