How to return the Promise.all fetch api json data?

前端 未结 5 2149
滥情空心
滥情空心 2021-01-05 15:45

How to I consume the Promise.all fetch api json data? It works fine to pull it if I don\'t use Promise.all. With .all it actually returns the values of the query in the cons

相关标签:
5条回答
  • 2021-01-05 15:53

    Using Promise.all to fetch the json responses of each of the API's-

    CODE:

    Promise.all([
      API_1_Promise,
      API_2_Promise,
      API_3_Promise])
      .then(allResults => console.log(allResults))
      .catch(err => console.log(err))
    

    In which API_1_Promise,API_2_Promise,API_3_Promise is defined as

    API_1_Promise = fetch(`API_URL_1`, {  *Add required headers* }).then(response => response.json())
    
    API_2_Promise = fetch(`API_URL_2`, {  *Add required headers* }).then(response => response.json())
    
    API_3_Promise = fetch(`API_URL_3`, { *Add required headers* }).then(response => response.json())
    

    RESPONSE: This will print the array of responses from all the API calls In console-->

    [JSON_RESPONSE_API1, JSON_RESPONSE_API2, JSON_RESPONSE_API3]
    
    0 讨论(0)
  • 2021-01-05 15:58

    You can just throw await in front of your Promise instead of awaiting each individual fetch

    await Promise.all([
        fetch('https://jsonplaceholder.typicode.com/todos/1'),
        fetch('https://jsonplaceholder.typicode.com/todos/2')
      ]).then(async([aa, bb]) => {
        const a =  aa.json();
        const b =  bb.json();
        return [a, b]
      })
      .then((responseText) => {
        console.log(responseText);
    
      }).catch((err) => {
        console.log(err);
      });
    

    Hope this helps

    0 讨论(0)
  • 2021-01-05 15:59

    Simplest solution is to repeat use of Promise.all, to wait for all .json() to resolve. Just use

    Promise.all([fetch1, ... fetchX])
    .then(result => Promise.all(result.map(v => v.json()))
    .then(result => {... result[0, ...X] available as objects})
    
    0 讨论(0)
  • 2021-01-05 16:10

    Aparently aa.json() and bb.json() are returned before being resolved, adding async/await to that will solve the problem :

    .then(async([aa, bb]) => {
        const a = await aa.json();
        const b = await bb.json();
        return [a, b]
      })
    

    Promise.all([
        fetch('https://jsonplaceholder.typicode.com/todos/1'),
        fetch('https://jsonplaceholder.typicode.com/todos/2')
      ]).then(async([aa, bb]) => {
        const a = await aa.json();
        const b = await bb.json();
        return [a, b]
      })
      .then((responseText) => {
        console.log(responseText);
    
      }).catch((err) => {
        console.log(err);
      });

    Still looking for a better explaination though

    0 讨论(0)
  • 2021-01-05 16:11

    Instead of return [aa.json(),bb.json()] use return Promise.resolve([aa.json(),bb.json()]). See documentation on Promise.resolve() .

    0 讨论(0)
提交回复
热议问题