async-await同步语法,消灭回调函数
async function xxx() {
...
}
(async function(){
...
})()
和promise的关系
how
async function fn1(){
return Promise.resolve(100)
}
const res1 = fn1()
res1.then(data => {
console.log('data', data)
})
!(async function() {
const data = await 400
console.log('data', data)
})()
!(async function() {
const p1 = Promise.reject('err')
const data = await p1
console.log(res)
})()
try...catch可捕获异常,代替promise的catch
!(async function() {
const p1 = Promise.reject('err')
try{
const res = await p1
console.log(res)
} catch(ex) {
console.error(ex)
}
})()
题
async function async1 () {
console.log('async1 start')
await async2()
console.log('async1 end')
}
async function async2 () {
console.log('async2')
}
console.log('script start')
async1()
console.log('script end')
script start
async1 start
async2
script end
async1 end
async function fn() {
return 100
}
(async function () {
const a = fn()
const b = await fn()
})()
(async function (){
console.log('start')
const a = await 100
console.log('a', a)
const b = await Promise.resolve(200)
console.log('b', b)
const c = await Promise.reject(300)
console.log('c', c)
console.log('end')
})
start
a 100
b 200