简体   繁体   English

Javascript-根据条件使用链接函数的不同部分

[英]Javascript - using different parts of chained functions, by conditions

generally in Javascript, say I have got this code: 通常用Javascript,说我有以下代码:

return (dispatch) => {
    return axios.post(`${ROOT_URL}/company`, data).then(companyResponse => {

    }).catch(error => {
        throw (error);
    });
};

Now, in some cases I want to call the "post" method with some parameters (as written above) and in other cases I'd like to use "put" with different params. 现在,在某些情况下,我想使用某些参数调用“ post”方法(如上所述),而在其他情况下,我想在不同的参数中使用“ put”方法。 Something like this: 像这样:

// Pseudo code
if(some condition){
    // use this: axios.put(`${ROOT_URL}/company`, data, config)
}
    // use this: axios.post(`${ROOT_URL}/company`, data)
}

What is the best practice for doing that? 最佳做法是什么?

You can use the bracket notation with the ternary operator to use post or put depending on condition. 您可以将括号符号与三元运算符一起使用,以根据条件使用桩或推杆。 You can also use the ternary operator to pass the config if the condition is met, and otherwise pass an empty object as config. 如果满足条件,您还可以使用三元运算符传递配置,否则将空对象作为配置传递。

axios[condition ? 'put' : 'post'](`${ROOT_URL}/company`, data, condition ? config : {})

You can also use axios config object to specify method: 您也可以使用axios config对象指定方法:

const method = condition ? 'put' : 'post' // ternary operator
axios({ method, url: `${ROOT_URL}/company`, data })
  .then(...)
  .catch(...)

Something like this 像这样

Yes, exactly like this. 是的,完全像这样。 Remember that promises are just values, you can pass them around and store them in variables or make them the results of expressions. 请记住,promise只是值,您可以传递它们并将它们存储在变量中或使它们成为表达式的结果。

return (dispatch) => {
    var promise;
    if (some condition)
        promise = axios.put(`${ROOT_URL}/company`, data, config);
    else
        promise = axios.post(`${ROOT_URL}/company`, data)
    return promise.then(companyResponse => {
        …
    });
}

Or use the conditional operator: 或使用条件运算符:

return (dispatch) => {
    return (some condition
      ? axios.put(`${ROOT_URL}/company`, data, config);
      : axios.post(`${ROOT_URL}/company`, data)
    ).then(companyResponse => {
        …
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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