用es6新语法 generator实现
function promiseFunc(step) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(step + 1)
}, 3000)
})
}
function promiseFuncReject(step) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(step + 1)
}, 3000)
})
}
function normalFunc(step) {
return step + 1
}
function* gen() {
let step = yield promiseFunc(0)
console.log(step)
step = yield promiseFunc(step)
console.log(step)
step = yield promiseFuncReject(step)
console.log(step)
step = yield normalFunc(step)
console.log(step)
return step
}
function genToAsync(genFunc) {
const gen = genFunc()
return new Promise((resolve, reject) => {
function next(val) {
let res
// 使用try catch捕获可能出现的错误,返回reject状态的promise
try {
res = gen.next(val)
} catch (error) {
return reject(error)
}
const { value, done } = res
if (done) {
// 如果done为true, 说明走完了,直接resolve
return resolve(value)
} else {
//如果done为false, 代表未走完, 继续
// value可能是promise、值、非promise函数。。。
return Promise.resolve(value).then(val => next(val)).catch(err => reject(err))
}
}
next()
})
}
genToAsync(gen)
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})