js异步

作者: 妮儿_smile | 来源:发表于2017-10-13 08:57 被阅读0次

    js异步编程4种方法(以jQuery的写法为例)  -- 来自阮一峰2012年的文章

    1.回调函数 

     function f1(callback) {setTimeout(function(){// f1的代码  callback()})} 

    => 使用  f1(f2)

    2.事件监听

      function f1(){setTimeout(function(){// f1的代码  f1.trigger('done')})} 

    => 使用  f1.trigger('done')

    3.发布/订阅  

    function f1(){setTimeout(function(){// f1的代码  jQuery.publish('done')})} 

    => 使用  jQuery.subscribe('done',f2). ps.完成后可以使用unsubscribe取消订阅

    4.Promise对象 

     function f1(){var dfd = $.Deferred() setTimeout(function(){// f1的代码 dfd.resolve() },500) return dfd.promise}

     => 使用   f1().then(f2) or f1().then(f2).then(f3) or f1().then(f2).fail(f3)

    相关文章

      网友评论

          本文标题:js异步

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