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

左心房为你撑大大i 提交于 2020-01-22 20:55:07

问题


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: []
|improve this question

回答1:


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




回答2:


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})



回答3:


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




回答4:


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]


来源:https://stackoverflow.com/questions/54896470/how-to-return-the-promise-all-fetch-api-json-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!