function fn1() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(1)
resolve()
}, 2000)
})
}
function fn2() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(2)
resolve()
}, 1000)
})
}
function fn3() {
return new Promise((resolve, reject) => {
console.log(3)
resolve()
})
}
// 顺序执行(利用回调)
fn1().then(() => {
fn2().then(() => {
fn3().then(() => {
console.log('end')
})
})
}) // 打印结果:1, 2, 3, end
// 顺序执行(利用Promise.resolve)
Promise.resolve()
.then(fn1)
.then(fn2)
.then(fn3)
.then(() => {
console.log('end')
}) // 打印结果:1, 2, 3, end
// 并行执行(利用Promise.all)
Promise.all([fn1(), fn2(), fn3()])
.then(() => {
console.log('end')
}) // 打印结果:3, 2, 1, end