第一次使用React或JavaScript完成投票后,如何返回可解决的Promise?

时间:2019-05-21 18:45:23

标签: javascript reactjs promise

嗨,我想返回在第一次民意调查结束后解决的诺言...

我有一个start_polling方法,我想对其进行修改,以便它返回一个promise,当items_promise得到解决时,它会得到解决...我不确定该怎么做。.

下面是代码,

componentDidUpdate(prevProps, prevState) {
    const {state, props} = this;
    const current_id = props.item && props.item.id;
    const prev_id = prevProps.item && prevProps.item.id;
    if (current_id !== prev_id) {
        this.stop_polling();
        this.setState(this.get_initial_state(), () => {
            this.start_polling();
    });
    } else {
        const prev_poll = this.should_poll(prevProps, prevState);
        const next_poll = this.should_poll(props, state);
        if (prev_poll !== next_poll) {
            if (next_poll) {
                this.start_polling();
            } else {
                this.stop_polling();
            }
        }
    }
}


start_polling = () => {
    if (this.should_poll(this.props, this.state)) {
        this.poll();
    }
};

poll = () => {
    let still_polling = true;
    if (this.cancel_poll_request) {
        this.cancel_poll_request();
    }
    const cancel_poll_promise = new Promise((resolve) => { 
        this.cancel_poll_request = resolve; });
        cancel_poll_promise.then(() => {
        still_polling = false;
        this.cancel_poll_request = undefined;
        clearTimeout(this.poll_timeout);
    });

    const items_promise = client.get_items(this.props.item.id,  
    cancel_poll_promise);
    items_promise.then((request) => {
        const next_items = [];
        let something_changed = false;
        for (const new_item of request.response) {
            const old_item = this.state.items.find(
                old_item =>
                    old_item.id === new_item.id);
            if (old_item) {
                next_items.push(old_item);
            } else {
                something_changed = true;
                next_items.push(new_item);
            }
    }

    if (something_changed) {
        const next_state = {items: next_items};
        this.setState(next_state);
    }

    }).then(() => {
    if (still_polling) {
        this.poll_timeout = setTimeout(this.poll, 100s);
    }
    }).catch(this.props.notifications.request_error);
};

有人可以帮我解决这个问题吗?

0 个答案:

没有答案