美文网首页
回调函数和异步任务

回调函数和异步任务

作者: 老胡写着玩 | 来源:发表于2021-10-30 14:10 被阅读0次

    回调函数

    当一个函数作为参数传入另一个函数中,并且它不会立即执行,只有当满足一定条件后该函数才可以执行,这种函数就称为回调函数。我们熟悉的定时器和Ajax中就存回调函数:

    setTimeout(function() {
      console.log('执行了回调函数');
    }, 3000)
    

    这里的回调函数就是function(){console.log('执行了回调函数')},在满足条件后执行。

    var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
            var result = xhr.responseText;
            console.log(result);
        }
    }
    
    xhr.open('get', 'http://www.baidu.com', true);
    xhr.send();
    

    这里的回调函数是 xhr.onreadystatechange绑定的函数,在xhr.send() 发送请求并拿到响应后执行。

    异步任务

    与之相对应的概念时“同步任务”,同步任务在主线程上排队执行,只有前一个任务执行完毕,才能执行下一个任务。异步任务不进行主线程,而是进入异步队列,前一个任务是否执行完毕不影响下一个任务的执行。

    xhr.open('get', 'http://www.baidu.com', true);
    xhr.send();
    
    setTimeout(function(){
        console.log('执行了回调函数');
    }, 3000)
    console.log('主函数');
    

    如果按照代码编写的顺序,应该先输出“执行了回调函数”,实际输出为:

    主函数
    执行了回调函数
    

    这种不阻塞后面任务执行的任务就叫做异步任务。

    相关文章

      网友评论

          本文标题:回调函数和异步任务

          本文链接:https://www.haomeiwen.com/subject/nksgaltx.html