Async/await函数和Promise的联系
async/await 解决了异步回调,可以以 同步代码 的形式 书写 异步的过程
- async 表示函数里有异步操作
- await 相当于 promise.then,表示后面有异步操作(setTomeout, ajax请求)
- async 函数的返回值是一个Promise对象,可以用then方法指定下一步的操作
- try…cache相当于promise catch
async getBdcdyhArr() {
// await 后面是一个Promise请求,相当于promise.then()
const response = await BdcdyService.getBdcdy('111')
return resonse
}
getBdcdyhArr.then(val => this.$emit('updateData', val)
关于try…catch和await二者有个注意点:
function xxx () {
const p = Promise.reject(err)
const res = await p
console.log('res', res)
}
// 会报错,reject返回的是rejected状态的Promise,而await 相当于promise then
// 此时可以拿try...catch来捕获,抛出异常
async function async1 () {
console.log('async1 start') // 2
await async2()
// await 后面都可以看作是 callback 里的内容,即异步
// 类似于 event loop,setTimeout()
// setTimeout(function () {console.log('async1 end')})
// Promise.then(() => console.log('async1 end'))
console.log('async1 end') // 5
}
async function async2() {
console.log('async2') // 3
}
console.log('js start') // 1
async1()
console.log('js end') // 4
----->进阶应用
async function async1(){
console.log('async1 start') // 2
await async2()
console.log('async1 end') // 7 错误----> 6
}
async function async2(){
console.log('async2') // 3
}
console.log('script start') // 1
setTimeout(function(){
console.log('setTimeout') // 6 错误----> 8
},0)
async1();
new Promise(function(resolve){
console.log('promise1') // 4
resolve();
}).then(function(){
console.log('promise2') // 8 错误----> 7
})
console.log('script end') // 5
1-5:同步代码执行完毕(event loop - call stack 被清空)
6-7:执行微任务
空:尝试触发DOM渲染
8:触发Event Loop,执行宏任务
继续做题…
async function fn() {
return 100
}
function xxx() {
const a = fn() // resolved状态的promise,async返回的是一个promise
const b = await fn() // 100
}
function test() {
console.log('start') // start
const a = await 100
console.log('a', a) // 100
const a = await Promise.resolve(200)
console.log('b', b) // 200
const a = await Promise.reject(300) // 报错
console.log('c', c) // 不打印
console.log('end') // 不打印
}