首页 > Web开发 > 详细

js使用generator函数同步执行ajax任务

时间:2018-07-26 17:29:57      阅读:177      评论:0      收藏:0      [点我收藏+]
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()
// 异步任务模型

js使用generator函数同步执行ajax任务

原文:https://www.cnblogs.com/zj911005/p/9372730.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!