1. promise
1.1 实现红绿灯
function red() {
console.log('red')
}
function green() {
console.log('green')
}
function yellow() {
console.log('yellow')
}
const light = (timer, cb) => {
return new Promise(resolve => {
setTimeout(() => {
cb()
resolve()
}, timer)
})
}
const step = function () {
Promise.resolve()
.then(() => {
return light(3000, red)
})
.then(() => {
return light(2000, yellow)
})
.then(() => {
return light(1000, green)
})
.then(() => {
return step()
})
}
step()
1.2 实现每秒自动加一
其实,这道题就是上面那道题的变形。
let count = 0
const addOne = () => {
count = count + 1
console.log(count)
}
const addOneByOneSecond = (timer, cb) => {
return new Promise(resolve => {
setTimeout(() => {
cb()
resolve()
}, timer)
})
}
const finalFunc = () => {
Promise.resolve()
.then(() => {
return addOneByOneSecond(1000, addOne)
})
.then(() => {
return finalFunc()
})
}
finalFunc()
1.3 Promise.all
const myPromiseAll = (iterable) => {
return new Promise((resolve, reject) => {
const promises = Array.from(iterable)
// 保存执行成功的个数
let count = 0
// 保存执行成功的结果
const result = []
promises.map((promise, index) => {
promise
.then((res) => {
result[index] = res
count += 1
if (promises.length === count) {
resolve(result)
}
})
.catch((err) => {
reject(err)
})
})
})
}