首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TextDecoder在ES6 Promise递归中失败

TextDecoder在ES6 Promise递归中失败
EN

Stack Overflow用户
提问于 2018-03-29 04:14:21
回答 1查看 108关注 0票数 1

我正在尝试查询一个以XML的ReadableStream作为响应的API。

下面的代码使用了递归Promise。递归,因为它有时不会在单个迭代中解码流,这就是让我头疼的原因。

虽然我成功地获取了数据,但由于某些原因,解码阶段有时无法完成,这让我相信这是因为流太大,无法进行一次迭代。

代码语言:javascript
复制
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));
}
EN

回答 1

Stack Overflow用户

发布于 2018-03-29 17:59:57

我认为,有时在当前迭代完成之前调用下一次迭代,会导致错误地连接已解码的XML。

我将函数从同步转换为异步,并将其作为组件的常规递归方法,而不是使用方法的递归promise。

代码语言:javascript
复制
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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49543395

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档