How to avoid multiple variable re-declarations on function outputs in JavaScript

前端 未结 6 1288
生来不讨喜
生来不讨喜 2021-01-24 16:37

Consider the following example

function doSomethingToAVariable(variable){
    return variable + 1
}

function doSomethingToAVariableASecondTime(variable){
    re         


        
6条回答
  •  醉梦人生
    2021-01-24 17:10

    In this case you're looking for what's called "function composition":

    var myVariable = doSomethingToAVariableLastly(doSomethingToAVariableASecondTime(doSomethingToAVariable(0)));
    

    but this is clearly not readable with such long function names.

    Promises are typically only useful for asynchronous operations, and whilst they'd work in this scenario, the result would be inefficient and would introduce async dependencies where none are needed:

    var promise = doSomethingToAVariable(0);
            .then(doSomethingToAVariableASecondTime);
            .then(doSomethingToAVariableLastly);
    

    since you can only access the final result from the end of the chain of .then callbacks:

    promise.then(function(myVariable) {
        // myVariable is now 6, and in scope
    }
    
    // but it's not in scope or usable here
    

提交回复
热议问题