如何 return Promise.all 获取 api json 数据?

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

如何使用 Promise.all 获取 api json 数据?如果我不使用 Promise.all,它可以很好地拉动它。使用 .all 它实际上 returns 控制台中查询的值,但由于某种原因我无法访问它。这是我的代码以及解析后它在控制台中的外观。

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

我想要的只是能够访问 data.qry1。我尝试使用 responseText[0].data.qry1 或 responseText[0]['data']['qry1'] 但它返回未定义。下面是 console.log responseText[0] 的输出。 console.log(aa) 给出响应 {type: "basic" ...

    Promise {<resolved>: {…}}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
data: {qry1: Array(35)}
errors: []

显然 aa.json()bb.json() 在解决之前返回,添加 async/await 将解决问题:

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

仍在寻找更好的解释

使用 return Promise.resolve([aa.json(),bb.json()]) 而不是 return [aa.json(),bb.json()]。请参阅有关 Promise.resolve() 的文档 .

最简单的解决方案是重复使用 Promise.all,等待所有 .json() 解决。 只需使用 :

Promise.all([fetch1, ... fetchX])
.then(results => Promise.all(results.map(r => r.json())) )
.then(results => { You have results[0, ..., X] available as objects })

使用 Promise.all 获取每个 API 的 json 响应-

代码:

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

其中API_1_Promise,API_2_Promise,API_3_Promise定义为

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

响应: 这将打印所有 API 调用的响应数组 在控制台-->

[JSON_RESPONSE_API1, JSON_RESPONSE_API2, JSON_RESPONSE_API3]

您可以直接将 await 放在您的 Promise 前面,而不是等待每个单独的获取

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

希望对您有所帮助

我遇到了同样的问题,我的目标是使 Promise.all() return 成为 array of JSON objects

let jsonArray = await Promise.all(requests.map(url => fetch(url)))
    .then(async (res) => {
        return Promise.all(
            res.map(async (data) => await data.json())
        )
    })

如果你需要它很短(复制粘贴人员的一个班轮:)

const requests = ['myapi.com/list','myapi.com/trending']
const x = await Promise.all(requests.map(url=>fetch(url))).then(async(res)=>Promise.all(res.map(async(data)=>await data.json())))