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