【问题标题】:How to return the Promise.all fetch api json data?如何返回 Promise.all 获取 api json 数据?
【发布时间】:2019-07-20 15:26:45
【问题描述】:

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

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) 给出 Response {type: "basic" ...

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

【问题讨论】:

标签: javascript promise fetch


【解决方案1】:

最简单的解决方案是重复使用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 })

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,我的目标是让 Promise.all() 返回 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())))
    

    【讨论】:

      【解决方案3】:

      您可以将await 放在您的 Promise 前面,而不是等待每个单独的 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);
        });
      

      希望对你有帮助

      【讨论】:

        【解决方案4】:

        使用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]
        

        【讨论】:

          【解决方案5】:

          使用return Promise.resolve([aa.json(),bb.json()]) 代替return [aa.json(),bb.json()]。请参阅Promise.resolve() 上的文档。

          【讨论】:

            【解决方案6】:

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

            仍在寻找更好的解释

            【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-08-17
            • 2019-11-13
            • 2020-08-06
            • 2014-07-01
            • 1970-01-01
            • 1970-01-01
            • 2018-02-20
            • 2022-07-11
            相关资源
            最近更新 更多