Promise 异步函数顺序执行


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

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)
})

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM