异步与同步
- 什么是
同步
?- 程序运行一般是
同步
的(synchronous),即按照书写的顺序执行。 - 例子
console.log('1') console.log('2') console.log('3') //输出结果为1 2 3 复制代码
- 程序运行一般是
- 什么是
异步
?异步
(asynchronous)与同步相对,即在前一个方法未执行完时,就开始运行后一个方法。- 例子:
console.log('1') setTimeout(()=>{ console.log('2') },0) console.log('3') //这个的输出结果会是 1 3 2 复制代码
- 总而言之,同步就是顺序执行,异步就是不完全按顺序执行。
回调
回调
(callback):把一个函数
作为参数
传入到另一个函数中,并且满足某个时机调用这个函数,那么这个传进去的函数叫做回调函数。- 例子:
function a(callback){ callback(); }; a(function(){}); //这样当 a 函数运行到 callback()的时候,函数回调。 复制代码
- 应用:
如果我们要获取一个异步的完毕信号,不用
回调
是获取不到的请看下面:
那要怎样才能获取到异步返回的东西呢下面我们用用神奇的回调:function doSomething() { let result = '' setTimeout(function() { result = "finished" return result }, 1000) } console.log(doSomething()) //undefined 复制代码
用了回调以后我轻易的拿到了异步的数据,问题解决。function doSomething(continueDoSomething) { let result = '' setTimeout(function() { result = "finished" continueDoSomething(result) }, 1000) } doSomething(function(result){ console.log(result)// "finished" }) 复制代码