// 经典 sleep 函数
function sleep(time=1000) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, time);
})
}
// 姿势正确的 async await 异常处理
const handleTest = async () => {
const data = await sleep().then((...args) => {
console.log('正确操作', args)
}, (...args) => {
console.log('假如遇到错误1', args)
}).catch((e) => {
console.log('假如遇到错误2', e)
}).finally(() => {
console.log('嘿嘿嘿...')
})
console.log(data)
console.log('哈哈哈!!!')
}
// 一秒执行一次
(async function () {
for(let i = 0; i < 10; i++) {
await sleep()
console.log(i + 1)
}
})()