blog icon indicating copy to clipboard operation
blog copied to clipboard

JavaScript 同步回调/异步回调

Open qingquan-li opened this issue 4 years ago • 0 comments

参考:


在 Chrome DevTools 中执行以下 JavaScript ,或者 $ node .js file

/**
 * 同步回调 function-callback-sync.js
 * 等待 4 秒才会 log 全部输出:
 * 传入的(匿名)回调函数( callback(); )在同步方法(syncFun)运行完成后(等待4秒)才被调用
 */

var syncFun = function(callback) {
    var start = new Date();
    while(new Date() - start < 4000) { // delay 4 sec
        ;
    }
    callback();
    console.log('log 2nd  同步方法返回');
};

syncFun(function() {
    console.log('log 1st  这是同步回调');
});

console.log('log 3rd  同步方法会阻塞当前逻辑');
/**
 * 异步回调 function-callback-async.js
 * log 1st、2nd 后,等待 4 秒后再 log 3rd:
 * 异步方法调用后立即返回,异步事件完成后(这里使用 setTimeout 超时事件模拟,
 * 实际还可以是 Ajax 、用户行为事件等异步事件),传入的回调函数才会被调用
 */

var asyncFun = function(callback) {
    setTimeout(callback, 4000); // delay 4 sec
    console.log('log 1st  异步方法返回');
};

asyncFun(function() {
    console.log('log 3rd  这是异步回调');
});

console.log('log 2nd  异步方法不会阻塞当前逻辑');

备注:平时使用的比较多的是「异步回调」,例如微信小程序里接口调用成功的回调函数 success (res) { }

qingquan-li avatar Mar 04 '20 16:03 qingquan-li