简体   繁体   中英

JavaScript callback doesn't seem to work

It's probably a simple problem, but I have the following function:

addValues();
function addValues() {
    addObsToMap(function() {
        addMeansToMap();
    });                 
}

They are defined as such:

function addObsToMap(callback) {
    console.log("addObsToMap");
    callback();
}                                                               

function addMeansToMap() {
    console.log("addMeansToMap");   
}   

What I want to do is call 'addObsToMap' before calling 'addMeansToMap', but that's not happening with the current code, as 'addMeansToMap' is currently being returned before 'addObsToMap'. What am I missing?

Are you sure? In js fiddle addobs is done first

https://jsfiddle.net/moym1n8c/

console.log('first');
addValues();   

results in :

first
addobjstomap
addmeanstomap

Seems to work perfectly fine..

But different browsers and different versions might have different implementations.

A change i would make would be to just pass the "addMeansToMap" function as the callback, instead of creating a new function to execute it.

 addValues(); function addValues() { addObsToMap(addMeansToMap); } function addObsToMap(callback) { console.log("addObsToMap"); callback(); } function addMeansToMap() { console.log("addMeansToMap"); } 

This way, if wanted, we can also more easily pass data from addObsToMap to addMeansToMap without needing a global variable.

  addValues(); function addValues() { addObsToMap(addMeansToMap); } function addObsToMap(callback) { console.log("addObsToMap"); callback("addMeansToMap"); } function addMeansToMap(arg) { console.log(arg); } 

Hard Coded addMeansToMap(); is called when you call your other function instead of passing it as a callback. To fix this just call addMeansToMap(); from the other function after the other code has executed.

function addObsToMap() {
     console.log("addObsToMap");   
     addMeansToMap();
} 

function addMeansToMap(){ 
     console.log("addMeansToMap");
} 

Using Parametric Callback Note also that you have not actually passed the function in as a callback when you call the function.

addValues(); 
function addValues(){ 
    addObsToMap(addMeansToMap);
}

The above way would work keeping the original Obs and Means functions the same.

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