当前位置:网站首页>实现异步的方法
实现异步的方法
2022-06-25 22:14:00 【Senora】
实现异步的方法
一、回调函数
回调是一个函数被作为一个参数传递到另一个函数里,在那个函数执行完后再执行。( 也即:B函数被作为参数传递到A函数里,在A函数执行完后再执行B )
回调函数是异步编程最基本的方法,回调不一定是异步
原理:利用定时器的工作原理将 f1 放入事件队列中去执行,哪怕延时是 0,也是如此,因此不堵塞程序运行。此处掌握定时器的工作原理。
假定有两个函数 f1 和 f2,后者等待前者的执行结果。
优点:简单,易理解和部署。
缺点:不利于代码的阅读和维护,各个部分之间高度耦合,流程很混乱,而且每个任务只能指定一个回调函数。
f1();
f2();
//如果f1是一个很耗时的任务,可以考虑改写f1,把f2写成f1的回调函数。
function f1(callback){
setTimeout(function () {
// f1的任务代码
callback();
}, 1000);
}
//执行代码就变成下面这样:
f1(f2);
二、事件监听
另一种思路是采用事件驱动模式。任务的执行不取决于代码的顺序,而取决于某个事件是否发生。
原理:利用定时器的原理去把 f1 放入事件队列里,等全部执行完毕之后,才会执行事件队列里的方法。
还是以 f1 和 f2 为例。首先,为f1绑定一个事件(这里采用的 jQuery 的写法)。
优点:比较容易理解,可以绑定多个事件,每个事件可以指定多个回调函数,而且可以“去耦合”,有利于实现模块化。
缺点:是整个程序都要变成事件驱动型,运行流程会变得很不清晰。
f1.on('done', f2);
//上面这行代码的意思是,当f1发生done事件,就执行f2。然后,对f1进行改写:
function f1(){
setTimeout(function () {
// f1的任务代码
f1.trigger('done');
}, 1000);
}
f1.trigger(‘done’) 表示,执行完成后,立即触发 done 事件,从而开始执行f2。
三、Promise对象
Promise 对象是 CommonJS 工作组提出的一种规范,目的是为异步编程提供统一接口思想,每一个异步任务返回一个 Promise 对象,该对象有一个 then 方法,允许指定回调函数。
比如,f1 的回调函数f2,可以写成:f1().then(f2);
优点:回调函数变成了链式写法,程序的流程可以看得很清楚,而且有一整套的配套方法,可以实现许多强大的功能。
缺点:编写和理解,都相对比较难。
function f1(){
var dfd = $.Deferred();
setTimeout(function () {
// f1的任务代码
dfd.resolve();
}, 500);
return dfd.promise;
}
边栏推荐
- dbca静默安装及建库
- Farsync simple test
- 11.1.2、flink概述_Wordcount案例
- Reading notes on how to connect the network - hubs, routers and routers (III)
- Redis之哨兵
- Mysql5.7 is in the configuration file my Ini[mysqld] cannot be started after adding skip grant tables
- 解决线程并发安全问题
- Servlet response下载文件
- Building cloud computers with FRP
- Shenzhen Taipower: the way of "communication" of the United Nations
猜你喜欢

DNS复习

dhcp复习

10.4.1 data console

Redis jump table

anchor free dection简介

How to configure SQL Server 2008 Manager_ Old bear passing by_ Sina blog

About the solution to prompt modulenotfounderror: no module named'pymongo 'when running the scratch project

【ROS进阶篇】第一讲 常用API介绍

EBS r12.2.0 to r12.2.6

JS to input the start time and end time, output the number of seasons, and print the corresponding month and year
随机推荐
10.4.1 données intermédiaires
Keil compilation run error, missing error: # 5: # includecore_ cm3.h_ Old bear passing by_ Sina blog
Oracle RAC cluster failed to start
Object array de duplication
Bit compressor [Blue Bridge Cup training]
Thrift入门学习
Resolve thread concurrency security issues
STEP7 master station and remote i/o networking_ Old bear passing by_ Sina blog
My blog is 2 years old and 167 days old today. I received the pioneer blogger Badge_ Old bear passing by_ Sina blog
Multi-Instance Redo Apply
Darkent2ncnn error
Servlet response下载文件
11.1.2、flink概述_Wordcount案例
毕业季 | 在不断探索中拟合最好的自己
Recommended system design
SSH review
Common problems encountered when creating and publishing packages using NPM
Ffmpeg version switching
被新冠后遗症困住15个月后,斯坦福学霸被迫缺席毕业典礼,现仍需每天卧床16小时:我本该享受20岁的人生啊...
10.2.2、Kylin_kylin的安装,上传解压,验证环境变量,启动,访问