开发者问题收集

react-native fetch async/await 响应过滤

2017-10-24
12809

我收到了来自服务器的响应,如 buildings : [record1, record2, ...] ,我只想从该响应中获取数组。我怎样才能从 Promise 中获取数组?我尝试了一些 async/await 的东西,但我不明白如何在此代码中使用它:

setupImpagination() {
    ....
    fetch(pageOffset, pageSize, stats) {
        return fetch(`http://localhost:3000/api/building/all?skip=${pageOffset}&limit=${pageSize}`)
            .then(response => {
            console.log('response.json() => ',response.json());
            response.json()
            })
            .catch((error) => {
            console.error(error);
            });

    }
    });
}
2个回答

.then 方式

 fetch(pageOffset, pageSize, stats) {
        return fetch(`http://localhost:3000/api/building/all?skip=${pageOffset}&limit=${pageSize}`)
            .then(response => {
               console.log('response.json() => ',response.json());
               response.json()
            }).then(responseJson => {
               return responseJson.buildings
            }).catch((error) => {
               console.error(error);
            });

        }
    });

async/await 方式:

 async fetch(pageOffset, pageSize, stats) {
       try {
           const response = await fetch(`http://localhost:3000/api/building/all?skip=${pageOffset}&limit=${pageSize}`);
           const responseJson = await response.json();
           return responseJson.buildings;
       } catch(error){
            console.error(error);
       }
Alexander Vitanov
2017-10-24
async function fetchData (url, { type = 'json' } = {}) {
  return await (await fetch(url))[type]();
}
// Example: 
(async () => {
  console.log(await fetchData('http://canskit.com', { type: 'text' }));
})();

作为ES7上的原生js,不针对react-native

Soul Clinic
2020-09-16