Javascript异步调用顺序执行方法

在使用异步回调的时候,我们经常会接住async等模块的帮助,但是有时候我们仅仅只需要一个异步调用同步执行的方法,似乎没必要使用那么多的代码,那么,异步调用顺序执行的方法如果自己写要怎么写呢?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
(function() {
var fns = [].slice.call(arguments);

fns.map(function(fn, i, fns){
fns[i] = function () {
var args = [].slice.call(arguments);
fn.apply(null, i + 1 === fns.length ? args : [fns[i + 1]].concat(args));
}
});

fns[0].call(null);
}(function(next) {
setTimeout(function() {
console.log('method 1');
next('method 1', 'complete!');
}, 200);
}, function(next, a, b) {
setTimeout(function() {
console.log(a, b);
console.log('method 2');
next('method 2', 'complete!');
}, 100);
}, function(a, b) {
console.log(a, b);
console.log('end');
}));

// method 1
// method 1 complete!
// method 2
// method 2 complete!
// end

一开始我一直处理不好next和data混合在一起的处理方法,直到我看到了一段类似的代码才醒悟。当前函数执行完之后调用next函数时,只有实际数据部分,但是下一个函数的定义却有一个next的第一参数,因此,我们需要讲原有的函数做替换,让他可以正常的接受当前函数传递过来的参数,并且执行的时候加上next参数。

文章目录
,