js多个异步请求
2019-07-16 本文已影响0人
凡凡的小web
js
function ajax(callback){
callback = callback || function(){};
var xhr = new XMLHttpRequest();
xhr.open("get","");
xhr.onload = function(res){ callback(res) };
xhr.send(null);
}
var when = (function(){
var i = 0,
len = 0,
data = [];
return function(array,callback){
callback = callback || function(){};
len = len || array.length;
var fn = array.shift();
fn(function(res){
i++;
data.push(res);
if(i < len){
when(array,callback);
} else {
callback(data);
}
});
};
})();
when([ajax,ajax],function(data){
console.log(data);
});
js多个异步请求,按顺序执行next
function nextRegister(){
var args = arguments;
var count = 0;
var comm = {};
function nextTime(){
count++;
if(count < args.length){
if(args[count] && Object.prototype.toString.call(args[count]) == '[object Function]'){
args[count](comm,nextTime);
}
}
}
if(args[count] && Object.prototype.toString.call(args[count]) == '[object Function]'){
args[count](comm,nextTime);
}
}
//创建多个异步的函数,注入到迭代器中
/*
comm:多个函数,公用的变量
next:调用下一个函数
* */
function fn1(comm,next){
console.log('1');
comm.age = 20;
next();
}
function fn2(comm,next){
next();
console.log('2');
console.log(comm.age);
}
function fn3(comm,next){
console.log('3');
}
//开始执行迭代
nextRegister(fn1,fn2,fn3);
ES6 方法
//模拟ajax异步操作1
function ajax1() {
const p = new Promise((resolve, reject) => {
setTimeout(function() {
resolve('ajax 1 has be loaded!')
}, 1000)
})
return p
}
//模拟ajax异步操作2
function ajax2() {
const p = new Promise((resolve, reject) => {
setTimeout(function() {
resolve('ajax 2 has be loaded!')
}, 2000)
})
return p
}
//等待两个ajax异步操作执行完了后执行的方法
const myFunction = async function() {
const x = await ajax1()
const y = await ajax2()
//等待两个异步ajax请求同时执行完毕后打印出数据
console.log(x, y)
}
myFunction()
参考
https://www.cnblogs.com/7qin/p/10261758.html
https://www.jianshu.com/p/054070c0c694
https://www.cnblogs.com/running1/p/9023427.html