Javascript 如何在reactjs中使用承诺而不是回调?

Javascript 如何在reactjs中使用承诺而不是回调?,javascript,reactjs,Javascript,Reactjs,我想在另一个函数完成后执行一个函数。我使用过回扣,但希望使用承诺。但我不知道该怎么做 下面是代码 this.set_function(this.save); //save is the callback method set_function = (callback) => { const some_var = {}; this.props.get_method.then(response => { some_var.data = response

我想在另一个函数完成后执行一个函数。我使用过回扣,但希望使用承诺。但我不知道该怎么做

下面是代码

this.set_function(this.save); //save is the callback method 

set_function = (callback) => {
    const some_var = {};
    this.props.get_method.then(response => {
        some_var.data = response;
        this.setState({selected: some_var});
        if(callback) {
            callback(this.props.id, some_var_data);
        }
    });
};

save = (id, some_var) => {
    const payload = {};
    payload.some_var = [some_var];

    client.update(id, payload)
        .then((request) => {
            this.save_data(id);
        });
};

在上面的代码中,一旦set_函数完成,就应该执行save函数。如上所示,它与回调一起工作。我怎样才能对承诺做出同样的承诺。有人能帮我做这个吗?

通过返回连锁承诺,让它充满希望:

set_function = (callback) => {
 return this.props.get_method.then(response => {      
    this.setState({selected: some_var});
    return {id: this.props.id, some_var };
  });
};
然后链接其他功能:

this.set_function.then(this.save)
const {id, data} = await set_function();
最后,对传递的对象进行去抖动:

save = ({ id, some_var }) => {

唯一的技巧是回调需要两个独立的东西(
this.props.id
一些变量数据
)。一个承诺只能有一个履行价值,因此您可以将其包装为一个对象:

set_function = () => this.props.get_method.then(response => {
    this.setState({selected: some_var});
    return {id: this.props.id, data: response};
});
请注意,由于您从
this.props.get_方法
获得了一个承诺,因此我们只是将其链接起来

(您的
某些变量数据
已经是一个对象,但它只有
数据
属性,所以我只是直接将
数据
包含在结果对象中。)

您可以这样使用它:

set_function()
.then(({id, data}) => {
    // use `id` and `data` here
})
.catch(error => {
    // Handle error here
});
(或者不要包含
.catch
,并将承诺链返回给其他将处理错误的对象。)

当然,如果您在
async
函数中使用它:

this.set_function.then(this.save)
const {id, data} = await set_function();
等待你的承诺 使用
async。。。wait
函数将返回一个承诺,该承诺将在函数完成后得到解决

set\u函数=async()=>{
const some_var={};
const response=等待this.props.get_方法;
一些变量数据=响应;
this.setState({selected:some_var});
返回[this.props.id,一些变量数据];
};
当您调用
set\u函数时
将返回一个承诺,这样您就可以
等待
。然后
它。像这样:

this.set_function()。然后(this.save);
//在哪里
save=([id,some_var])=>{
...
}

在这种情况下,您必须让
设置函数
返回一个
承诺

set_function = () => {
    const some_var = {};
    this.props.get_method.then(response => {
        some_var.data = response;
        this.setState({selected: some_var});
        return Promise.resolve({id: this.props.id, some_var: some_var_data})
    });
};

现在您可以这样使用它:

set_function().then(data => save(data)
这是一个可以玩的JSFIDLE