node.js, bluebird, poor control of execution path

后端 未结 1 1314
南笙
南笙 2021-01-25 18:31

I\'m trying to learn bluebird; I\'m not controlling execution as I want to. (This bluebird question came from an async.js question at Node.js, async module, concurrency.)

<
相关标签:
1条回答
  • 2021-01-25 18:45

    It's because your call to part1a(3) is not wrapped in a function so it's get called right away instead of waiting the previous promises to be resolved:

    function part1() {
        console.log('part1 start')
        // then() returns a promise so no need to create a new Promise
        return Promise.all([part1a(1), part1a(2)])
            .then(function (err) {
                if (err) console.log('part1 error after #1 and #2')
                else console.log('part1 done with #1 and #2')
            })
            // the issue was here, part1a() is a promise
            .then(function () {
                return part1a(3)
            })
            .then(function (err) {
                if (err) console.log('part1 error after #3')
                else console.log('part1 done')
            })
    }
    
    function part1a(i) {
        console.log('part1a start #' + i)
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.log('part1a done  #' + i)
                return resolve()
            }, 100)
        })
    }
    
    part1().then(function (err) {
        if (err) console.log('outermost code reported error' + err.message)
        else console.log('end of code')
    })
    
    0 讨论(0)
提交回复
热议问题