关于javascript处理异步的三种方式的简单介绍
// 1、很久以前处理异步
// callback 回调方式
function ajax(fn) {
setTimeout(() => {
console.log('异步')
fn()
}, 1000)
}
ajax(() => {
console.log('异步结束')
})
// 但是 如果请求多的话
// 会出现回调地狱
ajax(() => {
console.log('第一个异步处理结束')
ajax(() => {
console.log('第二个异步处理结束')
ajax(() => {
console.log('第三个异步执行结束')
})
})
})
// 2、es6 Promise方法
function delay(word) {
return new Promise((resolve, reject)=> {
setTimeout(() => {
resolve(word)
}, 2000)
})
}
// 使用promise
delay('老大')
.then(res => {
console.log(res)
return delay('老二')
})
.then(res => {
console.log(res)
return delay('老三')
})
.then(res => {
console.log(res)
})
// delay方法不变
// 使用 async + await !!! async一定要和await一起使用
async function start() {
// await 必须在async内部使用 等待一个异步
const wrod1 = await delay('佟丽娅')
console.log(wrod1)
const wrod2 = await delay('郭德纲')
console.log(wrod2)
const wrod3 = await delay('岳云鹏')
console.log(wrod3)
}
start()
可以复制下来直接用Node运行看结果