0

In his detailed explanation of asynchronous code in this question: Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference Fabrício Matté gives the following example:

// 1. Call helloCatAsync passing a callback function,
//    which will be called receiving the result from the async operation
helloCatAsync(function(result) {
    // 5. Received the result from the async function,
    //    now do whatever you want with it:
    alert(result);
});

// 2. The "callback" parameter is a reference to the function which
//    was passed as argument from the helloCatAsync call
function helloCatAsync(callback) {
    // 3. Start async operation:
    setTimeout(function() {
        // 4. Finished async operation,
        //    call the callback passing the result as argument
        callback('Nya');
    }, 2000);
}

I am trying to remove the anonymous function (I find it easier to read & understand the code that way). How should I do that?

Community
  • 1
  • 1
JDelage
  • 13,036
  • 23
  • 78
  • 112
  • 1
    Yes, exactly that. You even might want to make the callback passed to `setTimeout` a function declaration as well. – Bergi May 05 '16 at 22:13
  • 1
    I would suggest to place the function declaration above the place where the function is used. You code is absolutely valid, but [hoisting](https://speakingjs.com/es5/ch16.html#_variable_declarations_are_hoisted) is a tricky thing and should be used with caution. – Роман Парадеев May 05 '16 at 22:20
  • Thanks - moving the code into a new answer, which I'll accept in a couple days. – JDelage May 05 '16 at 23:28

1 Answers1

0
function helloCatAsync(callback,aString){
  setTimeout (function(){
    callback(aString);
    },2000);
}
function shout (param) {
  alert(param);
}
helloCatAsync(shout,'Nya');
JDelage
  • 13,036
  • 23
  • 78
  • 112