需求:实现1s后控制台输出1,2s后输出2,3s后输出3
实现一:通常我们大多数情况下会使用setTimeout来进行嵌套实现
setTimeout(function () {
console.log(1)
setTimeout(function () {
console.log(2)
setTimeout(function () {
console.log(3)
}, 3000)
}, 2000)
}, 1000)
实现二:生成器函数来实现(生成器函数的特点,函数名称前有*号,通过yield来执行,不能直接调用,调用的时候须通过next()进行调用
)------成功解决回调地狱的问题
function one() {
setTimeout(function () {
console.log(1)
iterator.next()
}, 1000)
}
function two() {
setTimeout(function () {
console.log(2)
iterator.next()
}, 2000)
}
function three() {
setTimeout(function () {
console.log(3)
iterator.next()
}, 3000)
}
function* getTime() {
yield one();
yield two();
yield three();
}
getTime()
let iterator = getTime()
iterator.next()
注意:
注意:next(‘可以传递参数’) 传递的参数为yield 语句的返回值