简体   繁体   中英

How to check meteor.call method ran successfully?

I am using meteor/react. I have two components. I want to pass method from one:

saveNewUsername(newUsername) {
    Meteor.call('setNewUsername', newUsername, (error) => {
        if(error) {
            Materialize.toast(error.reason, 4000);
        } else {
            Materialize.toast('Username changed!', 4000);
        }
    });
}

And than I need to check it for success:

    handleSaveOption() {
        const { howToChangeOption } = this.props;
        const optionValue = this.option.value.trim();
        if(howToChangeOption(optionValue)) {
            this.setState((prevState) => ({
                startToChange: !prevState.startToChange,
            }));
        }
    }

So, how to check Meteor.call for success and return true or false ? Thanks!

Solved with promises. Maybe anyone has better solution?

    saveNewUsername(newUsername) {
        return new Promise((resolve, reject) => {
            Meteor.call('setNewUsername', newUsername, (error) => {
                if(error) {
                    Materialize.toast(error.reason, 4000);
                    reject();
                } else {
                    Materialize.toast('Username changed!', 4000);
                    resolve();
                }
            });
        });
    }

    handleSaveOption() {
        const { howToChangeOption } = this.props;
        const optionValue = this.option.value.trim();
        howToChangeOption(optionValue).then(() => {
            this.setState((prevState) => ({
                startToChange: !prevState.startToChange,
            }));
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM