最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - react-native fetch asyncawait response filtering - Stack Overflow

programmeradmin4浏览0评论

I have response from my server like buildings : [record1, record2, ...] and I want to get only the array from that response. How can I get just the array from the Promise? I have tried some async/await things but I didn't understand how to use it in this code:

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

    }
    });
}

I have response from my server like buildings : [record1, record2, ...] and I want to get only the array from that response. How can I get just the array from the Promise? I have tried some async/await things but I didn't understand how to use it in this code:

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

    }
    });
}
Share Improve this question edited Oct 24, 2017 at 22:57 sideshowbarker 88.2k29 gold badges215 silver badges211 bronze badges asked Oct 24, 2017 at 20:01 imalik8088imalik8088 1,6416 gold badges23 silver badges43 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 16

.then way

 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 way:

 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);
       }
async function fetchData (url, { type = 'json' } = {}) {
  return await (await fetch(url))[type]();
}
// Example: 
(async () => {
  console.log(await fetchData('http://canskit.', { type: 'text' }));
})();

As the original js on ES7, not aim at react-native

发布评论

评论列表(0)

  1. 暂无评论