promise和async函数
promise
let p = new Promise((resolve)=>{
resolve("hello world")
})
p.then((data) => {
console.log(data) // hello world
})
async函数
// async函数的返回值是promise对象
async function fun(){
return 1
}
let a = fun()
console.log(a) // Promise { 1 }
fun().then((data)=>{
console.log(data) // 1
})
await
let p1 = new Promise((resolve) => {
resolve(1)
})
let p2 = new Promise((resolve) => {
resolve(2)
})
async function fun(){
let a = await p1
let b = await p2
console.log(a) // 1
console.log(b) // 2
}
fun()
async function fun1(){
let data = await fun2()
console.log(data) // 相当于then中的代码
}
async function fun2(){
console.log(data) // 同步
return 100
}
fun1()
// 执行顺序是 200 100
例子-执行顺序
console.log(1)
async function async1(){
await async2()
console.log(2)
}
async function async2(){
console.log(3)
}
async1()
setTimeout(function () {
console.log(4)
},0)
new Promise((resolve)=>{
console.log(5)
resolve()
}).then(()=>{
console.log(6)
}).then(()=>{
console.log(7)
})
console.log(8)
// 1358267
- 同步
- process.nextTick
- 微任务(promise.then)
- 宏任务(计时器,ajax,读取文件)
- setImmediate