javascript – react-native fetch async / await response filtering
作者:互联网
我的服务器响应如建筑物:[record1,record2,…],我想从该响应中只得到数组.我怎样才能从Promise获得数组?我尝试了一些异步/等待的东西,但我不明白如何在这段代码中使用它:
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);
});
}
});
}
解决方法:
然后
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);
});
}
});
异步/等待方式:
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);
}
标签:javascript,async-await,promise,react-native,fetch-api 来源: https://codeday.me/bug/20190715/1464931.html