这里有一些代码,加上我期望得到的和我得到的代码。
问题:
var Promise = require('bluebird')
function part1() {
console.log('part1 start')
return new Promise(function(resolve, reject) {
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')
}
)
.then(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')
}
)
我期待
part1 start
part1a start #1
part1a start #2
part1a done #1 // these two could
part1a done #2 // reverse
part1 done with #1 and #2
part1a start #3
part1a done #3
part1 done
end of code
我得到了
part1 start
part1a start #1
part1a start #2
part1a start #3
part1a done #1
part1a done #2
part1a done #3
part1 error after #1 and #2
part1 done
问题(为方便读者而重复):
提前致谢。
答案 0 :(得分:2)
这是因为您对part1a(3)
的调用未包含在函数中,因此可以立即调用它,而不是等待之前的承诺得到解决:
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')
})