我有一个要关注的网址列表,并希望将结果存储在数组中。当前的实现是使用map来获取和when.all来等待。如下所示:
const when = require('when');
}).then((responseJson) => {
return responseJson._embedded.leases.map(
lease => fetch(lease._links.self.href, {headers: {'Access-Control-Expose-Headers': 'ETag'}}));
}).then(leasePromises => {
return when.all(leasePromises);
}).then((leases) => {
var obj = leases.toString();
console.log("leasesJSON = " + obj);
console.log("leases[0]0= " + leases[0]);
console.log("leases[0]1= " + JSON.stringify(leases[0]));
console.log("leases[0]2= " + leases[0].json());
console.log("leases[0]3= " + JSON.stringify(leases[0].json()));
this.setState({
isLoading: false,
leases: leases,
attributes: Object.keys(this.schema.properties)
});
}).catch((error) => {
console.error("loadDataFromServer error = " + error);
});
但是render()方法抱怨'租约'对象是空的。
追踪结果:
leasesJSON = [object Response],[object Response]
leases[0]0= [object Response]
leases[0]1= {}
leases[0]2= [object Promise]
leases[0]3= {}
所以我的问题是:
答案 0 :(得分:3)
fetch API的响应具有.json()
方法(如您所知),这是异步的;它回报了一个承诺
因此,您必须等待它才能从服务器返回实际对象;这可能是造成你问题的原因。
}).then((responseJson) => {
return responseJson._embedded.leases.map(
lease => fetch(lease._links.self.href, {headers: {'Access-Control-Expose-Headers': 'ETag'}}));
}).then(leasePromises => {
return when.all(leasePromises);
}).then(leasesResponses => {
return when.all(leasesResponses.map(response => response.json()));
}).then(leases => {
// leases is finally what you expected them to be!
})
API是以这种方式构建的,因为您可以立即对响应状态/标头进行操作,而无需等待响应主体完全下载/解析。