带有命名函数的Canonical asynch回调示例

时间:2016-05-05 21:46:37

标签: javascript asynchronous callback

在这个问题中他对异步代码的详细解释: Why is my variable unaltered after I modify it inside of a function? - Asynchronous code referenceFabrícioMatté给出了以下例子:

// 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);
}

我正在尝试删除匿名函数(我发现它更容易阅读并且以这种方式理解代码)。我该怎么做?

1 个答案:

答案 0 :(得分:0)

function helloCatAsync(callback,aString){
  setTimeout (function(){
    callback(aString);
    },2000);
}
function shout (param) {
  alert(param);
}
helloCatAsync(shout,'Nya');