Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda