第一种是我们使用jQuery中ajax方法就是经典的回调方法
$.ajax({
url: '/path/to/file',
dataType: 'json',
data: {
param1: 'value1'
},
success(data1) {
$.ajax({
url: '/path/to/file',
dataType: 'json',
data: {
param1: 'value1'
},
success(data2) {
$.ajax({
url: '/path/to/file',
dataType: 'json',
data: {
param1: 'value1'
},
success(data3) {
}
error() {
}
})
}
error() {
}
})
}
error() {
}
});
第二种我们改为Promise封装来请求
Promise.all([
$.ajax({url:'/path/to/file'},dataType: 'json',),
$.ajax({url:'/path/to/file'},dataType: 'json',),
$.ajax({url:'/path/to/file'},dataType: 'json',),
]).then(result=>{
},err=>{
});
第三种我们改为Generator封装来请求
runner(function *(){
let data1 = yield $.ajax({url:'/path/to/file'},dataType: 'json',);
let data2 = yield $.ajax({url:'/path/to/file'},dataType: 'json',);
let data3 = yield $.ajax({url:'/path/to/file'},dataType: 'json',);
})
当然我们这里的runner也附上源码是一个封装好的回调
function runner(_gen) {
return new Promise((resolve, reject) => {
var gen = _gen;
_next();
function _next(_last_res) {
var res = gen.next(_last_res);
if (!res.done) {
var obj = res.value;
if (obj instanceof Promise) {
obj.then((res) => {
_next(res);
}, (err) => {
reject(err);
})
} else if (typeof obj == "function") {
if (obj.constructor.toString().startWith("function GeneratorFunction()")) {
runner(obj).then(res => _next(res), reject);
} else if (condition) {
_next(obj());
} else {
_next(obj);
}
} else {
resolve(res.value)
}
}
}
});
};
大家也可以通过 cnpm i yield-runner-blue 去下载这个
最后我们对比一下三种写法的适用场景
- 普通的Ajax回调适用于一个请求不需要其他代码支持
- Promise适用于读取大量数据的请求,写法更像同步代码易读
- 生成器封装则需要事先写好回调的函数支持,但在有逻辑的异步请求下则方便很多 yield自动帮你隔开请求中所需要的逻辑代码而使用Promise则需要很多then方法来隔开中间的判断层