Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 console but for some reason I'm not able to access it. Here is my code and how it looks in the console after it resolves.

Promise.all([
    fetch('data.cfc?method=qry1', {
        method: 'post',
        credentials: "same-origin", 
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: $.param(myparams0)
    }),
    fetch('data.cfc?method=qry2', {
        method: 'post',
        credentials: "same-origin", 
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: $.param(myparams0)
    })
]).then(([aa, bb]) => {
    $body.removeClass('loading');
    console.log(aa);
    return [aa.json(),bb.json()]
})
.then(function(responseText){
    console.log(responseText[0]);

}).catch((err) => {
    console.log(err);
});

All I want is to be able to access data.qry1. I tried with responseText[0].data.qry1 or responseText[0]['data']['qry1'] but it returned undefined. This below is the output from console.log responseText[0]. The console.log(aa) gives Response {type: "basic" ...

    Promise {<resolved>: {…}}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
data: {qry1: Array(35)}
errors: []
like image 483
Dong Avatar asked Feb 27 '19 01:02

Dong


People also ask

How do I return a promise from fetch API?

Because fetch() returns a promise, you can simplify the code by using the async/await syntax: response = await fetch() . You've found out how to use fetch() accompanied with async/await to fetch JSON data, handle fetching errors, cancel a request, perform parallel requests.

How do I get json from fetch response?

To get JSON from the server using the Fetch API, you can use the response. json() method. The response. json() method reads the data returned by the server and returns a promise that resolves with a JSON object.

Does .json return a promise?

The json() method returns a Promise. Remember, when returning a Promise, it is still pending because it is asynchronous (assuming the data is not there yet). So to get the data AFTER using the json() method, you need to use another then() method so it will just return the data after it arrives.

Does fetch returns a promise?

Due to the asynchronous nature of requests the outer code will already have returned by the time the promise resolves. It can be hard to get your head around at first, but it's much the same as a "traditional" AJAX request - you handle the response in a callback.


2 Answers

The simplest solution would be to repeat the use of Promise.all, to just wait for all .json() to resolve. Just use :

Promise.all([fetch1, ... fetchX])
.then(results => Promise.all(results.map(r => r.json())) )
.then(results => { You have results[0, ..., X] available as objects })
like image 176
adyry Avatar answered Oct 08 '22 12:10

adyry


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

like image 33
Taki Avatar answered Oct 08 '22 13:10

Taki