js使用generator函数同步执行ajax任务
更新时间:2017年09月05日 11:42:26 作者:在这个肆意的青春岁月
这篇文章主要为大家详细介绍了js使用generator函数同步执行ajax任务,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了js使用generator函数同步执行ajax任务的具体代码,供大家参考,具体内容如下
function request(url, callback) { fetch(url, {mode: 'cors', credentials: 'include', headers: new Headers({ 'X-Requested-With': 'XMLHttpRequest' })}) .then(response => response.text()) .then(text => { console.log(url); console.log(text); callback(text); }) .catch((e) => console.log(e)); } var iterator = null; function getData(src){ request(src, function(response){ iterator.next(JSON.parse(response)); }) } function getTpl(src){ request(src, function(response){ iterator.next(response); }); } // 同步任务 function render(data, tpl){ for(var i in data) { tpl = tpl.replace("${"+i+"}", data[i]); } return tpl; } // 主逻辑 var getArticles = function* (src){ console.log('begin') var data = yield getData(src) var tpl = yield getTpl(data.tpl) var res = render(data, tpl) console.log(res) } iterator = getArticles('data.json') // 开始执行 iterator.next() // 异步任务模型
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
在javascript中随机数 math random如何生成指定范围数值的随机数
本篇文章给大家介绍在javascript中随机数math random如何生成指定范围数值的随机数,由于math.random生成了一个伪随机数,之后还要经过我们的后期处理。对随机数math random感兴趣的朋友一起了解了解吧2015-10-10微信小程序登录对接Django后端实现JWT方式验证登录详解
这篇文章主要介绍了微信小程序登录对接Django后端实现JWT方式验证登录详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-07-07
最新评论