简体   繁体   中英

dynamically create the functions based on the length of the given variable

I have a function call “getDocID” which has been defined in some other JS library, for which we can pass a callback function myCallback.

To get the ID's for more than one we have to chain it, we need to call the function like following, which works fine.

function setDocIds(){
    const testValues = ["2980", "2981","2982"];
    const optID = "someValue";
    var myCallback_2 = function (result2){
        var appID = result2.ID;
        document.getElementById("div_2").innerHTML = appID; 
    } 
    var myCallback_1 = function (result1){
        var appID = result1.ID;
        document.getElementById("div_1").innerHTML = appID; 
        getDocID(optID, testValues[2], myCallback_2);
    }
    var myCallback = function (result){
        var appID = result.ID;
        document.getElementById("emailtemplate").innerHTML = appID;
        getDocID(optID, testValues[1], myCallback_1);
    }
    getDocID(optID, testValues[0], myCallback);
}

Can anyone guide me to optimize the above code and to create the functions dynamically based on the length of the testValues.

Using Array#forEach and scoping.

 function getDocID(id, num, callback){ callback({ID:`optId: ${id} and testVal: ${num}`}); } function setDocIds() { const testValues = ["2980", "2981", '2982']; const optID = "someValue"; testValues.forEach((n, i) => { getDocID(optID, n, function(result) { const appID = result.ID; const id = i === 0 ? "emailtemplate" : `div_${i}`; document.getElementById(id).innerHTML = appID; }); }); } setDocIds(); 
 <div id="emailtemplate"></div> <div id="div_1"></div> <div id="div_2"></div> 

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