看一个最简单例子:
function x() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('hello js')
}, 3000)
})
}
async function test() {
let n = await x()
console.log(n)
console.log('hello world')
}
test()
await后面必须跟一个返回promise的函数
这个代码块必须用async关键字声明
那如何捕捉promise里面失败呢?
用 try catch
function x() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('出错啦')
}, 3000)
})
}
async function test() {
try {
let n = await x()
console.log(n)
} catch(err) {
console.log(err)
}
console.log('hello world')
}
test()
那么如何在async函数里面使用多个异步呢?还是要用到promise
function x() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('hello')
}, 3000)
})
}
async function test() {
try {
let n = await Promise.all([x(), x()])
console.log(n)
} catch(err) {
console.log(err)
}
console.log('hello world')
}
test()
总结:
1,使用async function声明一个一步函数
2,await关键字后面跟一个promise函数
3,await 关键字仅仅在 async function中有效
4,这个async function返回的也是一个promise