Promise 处理异步代码相对于纯回调函数比较有序明了,但是对于同步函数写法还是挺繁琐的,下面有两种语法糖让异步更加清晰简洁
像指针一样下移,有点像在debug代码
function* gen() {
yield 1
yield 2
yield 3
}
let g = gen()
console.log(g.next())
console.log(g.next())
console.log(g.next())
console.log(g.next())
- 中断并完成下移
return()
function* gen() {
yield 1
yield 2
yield 3
}
let g = gen()
console.log(g.next())
console.log(g.next())
console.log(g.return('完成'))
console.log(g.next())
- 中断并抛出异常
throw()
function* gen() {
try {
yield 1
yield 2
yield 3
} catch(e) {
console.log(e)
}
}
let g = gen()
console.log(g.next())
console.log(g.next())
console.log(g.throw('异常'))
console.log(g.next())
function promise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('resolved')
}, 1000)
})
}
function* generate() {
promise().then((res) => {
console.log(res)
})
}
function fn() {
const res = generate().next()
console.log(res)
}
fn()
现在发现,异步代码不需要then
回调了,看起来和同步函数写法一样
不过现在我们有了async
、await
函数,将生成器进一步封装,也可以说出语法糖
使用Promise 写法写一个简单的例子
function promise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('resolved')
}, 1000)
})
}
function fn() {
promise().then((res) => {
console.log(res)
})
}
fn()
改写成 async
函数
async function asyncFn() {
console.log(await promise())
}
asyncFn()
async 和 then 一样 可以达到同一个的效果,而且代码中没有回调函数的影子了
多条异步链的情况
function promise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1)
}, 1000)
})
}
function fn() {
const p = promise().then((res) => {
console.log('第一个then', res)
return res === 2 ? new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2)
}, 500)
}) : new Promise((resolve, reject) => {
setTimeout(() => {
reject(3)
}, 500)
})
}).then((res) => {
console.log('第二个then', res)
}).catch((err) => {
console.log('异常', err)
})
}
fn()
使用 async 改写
function promise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1)
}, 1000)
})
}
function promise2() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2)
}, 500)
})
}
function promise3() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(3)
}, 500)
})
}
async function asyncFn() {
const step1_res = await promise()
console.log('第一步的结果:', step1_res)
try {
if (step1_res === 2) {
console.log('第二步的结果:', await promise2())
} else {
console.log('第二步的拒绝的结果:', await promise3())
}
}
catch(err) {
console.log('异常:', err)
}
}
asyncFn()
用同步的代码写出了异步的效果