我正在尝试查询一个以XML的ReadableStream作为响应的API。
下面的代码使用了递归Promise。递归,因为它有时不会在单个迭代中解码流,这就是让我头疼的原因。
虽然我成功地获取了数据,但由于某些原因,解码阶段有时无法完成,这让我相信这是因为流太大,无法进行一次迭代。
componentDidMount() {
fetch("http://thecatapi.com/api/images/get?format=xml&size=med&results_per_page=9")
.then((response) => {
console.log('fetch complete');
this.untangleCats(response);
})
.catch(error => {
this.state.somethingWrong = true;
console.error(error);
});
}
untangleCats({body}) {
let reader = body.getReader(),
string = "",
read;
reader.read().then(read = (result) => {
if(result.done) {
console.log('untangling complete'); // Sometimes not reaching here
this.herdingCats(string);
return;
}
string += new TextDecoder("utf-8").decode(result.value);
}).then(reader.read().then(read));
}发布于 2018-03-29 17:59:57
我认为,有时在当前迭代完成之前调用下一次迭代,会导致错误地连接已解码的XML。
我将函数从同步转换为异步,并将其作为组件的常规递归方法,而不是使用方法的递归promise。
constructor({mode}) {
super();
this.state = {
mode,
string: "",
cats: [],
somethingWrong: false
};
}
componentDidMount() {
fetch("http://thecatapi.com/api/images/get?format=xml&size=med&results_per_page=9")
.then( response => this.untangleCats( response.body.getReader() ) )
.catch(error => {
this.setState({somethingWrong: true});
console.error(error);
});
}
async untangleCats(reader) {
const {value, done} = await reader.read();
if (done) {
this.herdingCats();
return;
}
this.setState({
string: this.state.string += new TextDecoder("utf-8").decode(value)
});
return this.untangleCats(reader);
}https://stackoverflow.com/questions/49543395
复制相似问题