promise顺序执⾏的⼏种⽅法const p1 = new Promise(resolve => {
setTimeout(() => {
resolve(1)
}, 1000)
})
const p2 = new Promise(resolve => {
setTimeout(() => {
resolve(2)
}, 3000)
})
const p3 = new Promise(resolve => {
setTimeout(() => {
resolve(3)
}, 2000)
})
const p4 = new Promise(resolve => {
setTimeout(() => {
resolve(4)
}, 1500)
})
const ps = [p1, p2, p3, p4]
// ⽅式⼀,递归
const run = (p) => {
p.then((d) => {
console.log(d)
const nextP = ps[ps.findIndex(f => f === p) + 1]
if (nextP) {
run(nextP)
}
})
}
run(ps[0])
// ⽅式⼆,generator 函数,也是 co 库核⼼
const run = (gen) => {
const it = gen()
let ret = it.next()
function step () {
if (!ret.done) {
ret.value.then(d => {
console.log(d)
ret = it.next(d)
step()
})
}
}
step()
await和async使用方法}
run(function *() {
for (let p of ps) {
yield p
}
})
// ⽅式三,组成 then 链
const run = () => {
let p = solve()
ps.forEach(item => {
p = p.then(() => item).then(console.log)
})
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论