Promise 异步函数顺序执行

可以满足需求,且使用方法和Promise.all统一

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
33
34
35
36
37
38
39
40
41
42
43
44
var a = function() {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            console.log('a')
            resolve('a')
        }, 1000)
    })
}
 
var b = function(data) {
    return new Promise(function(resolve, reject) {
        console.log('b')
        resolve(data +'b')
    })
}
 
var c = function(data) {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            console.log('c')
            resolve(data +'c')
        }, 500)
    })
}
 
// 组织函数队列
function reduce(arr) {
    var sequence = Promise.resolve()
 
    arr.forEach(function(item) {
        sequence = sequence.then(item)
    })
 
    return sequence
}
 
// 顺序执行函数队列
reduce([a, b, c])
.then(function(data) {
    console.log(data)// abc
})
.catch(function(e) {
    console.log(e)
})

  

posted @   麦君  阅读(5922)  评论(0)    收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示