简体   繁体   中英

How to use callback function in javascript?

I want to change this code to use a callback function. I would like the program to call the ExecuteScriptForEdit after calling DynamicLoadScriptForEdit() , but this code doesn't work.

window.onload = function() {
  DynamicLoadScriptForEdit('/temps/F.js', function(err) {
    ExecuteScriptForEdit();
  }); //네트워크가 좋으면 상관없지만 안좋으면 동기화가 실패, 콜백으로 가야함
}

function DynamicLoad(source) {
    var script = document.createElement('script');
    script.src = source;
    script.onload = function() {
        //do stuff with the script 
    };
    document.head.appendChild(script);
}

function DynamicLoadScriptForEdit(source, callback) {
    DynamicLoad(source);
    OnButton('ID_Button_Test');
}

Please help me. Thank you.

To achieve this you can pass the function you provide to DynamicLoadScriptForEdit() in the callback parameter to the lower level functions before calling it in the onload handler of the script. Try this:

window.onload = function() {
    DynamicLoadScriptForEdit('/temps/F.js', function(err) {
        ExecuteScriptForEdit();
    });
}

function DynamicLoadScriptForEdit(source, callback) {
    DynamicLoad(source, callback); // provide callback function
    OnButton('ID_Button_Test');
}

function DynamicLoad(source, callback) { // receive callback function here
    var script = document.createElement('script');
    script.src = source;
    script.onload = function() {
        // do stuff with the script 

        callback && callback(); // call here
    };
    document.head.appendChild(script);
}

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