总结异步编程的六种方式
单线程
工作,也就是只有一个脚本执行完成后才能执行下一个脚本,两个脚本不能同时执行,如果某个脚本耗时很长,后面的脚本都必须排队等着,会拖延整个程序的执行。
那么如何让程序像人类一样可以多线程工作呢?
以下为几种异步编程方式的总结,希望与君共勉。
-
回调函数 -
事件监听 -
发布订阅模式 -
Promise -
Generator (ES6) -
async (ES7)
function f1() {setTimeout(function(){console.log('先执行 f1')},1000)}function f2() {console.log('再执行 f2')}
回调函数
回调函数,将同步操作变成异步操作,f1 不会阻塞程序的运行,f2 也无需空空等待,例如 JQuery 的 ajax。
function f1(f2){setTimeout(function(){console.log('先执行 f1')},1000)f2()}function f2() {console.log('再执行 f2')}
事件监听
$(document).ready(function(){console.log('DOM 已经 ready')});
发布订阅模式
//订阅done事件$('#app').on('done',function(data){console.log(data)})//发布事件$('#app').trigger('done,'haha')
Promise
export default function getMethods (url){return new Promise(function(resolve, reject){axios.get(url).then(res => {resolve(res)}).catch(err =>{reject(err)})})}
getMethods('/api/xxx').then(res => {console.log(res)}, err => {console.log(err)})
Generator
function *generatorDemo() {yield 'hello';yield 1 + 2;return 'ok';}
var demo = generatorDemo()
demo.next() // { value: 'hello', done: false }demo.next() // { value: 3, done: false }demo.next() // { value: 'ok', done: ture }demo.next() // { value: undefined, done: ture }
async
async function demo() {try {await new Promise(function (resolve, reject) {// something});} catch (err) {console.log(err);}}
demo().then(data => {console.log(data) //})
参考文献
https://developers.google.com...
http://es6.ruanyifeng.com/
如果觉得本文有帮助,欢迎多多转发点赞,推荐给更多的小伙伴哟
