基本使用
async函数返回的是一个Promise,能够进行Promise的相关操作,函数内部返回的结果会成为then方法回调函数的参数
async function asyncfunc(){
return "这是一个async函数"
}
asyncfunc()
asyncfunc().then(function(info){console.log(info)})
当函数执行中遇到await,需等异步操作完成,才会执行后面的代码
async function asyncfunc() {
let now = new Date().getTime();
await new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, 2000)
})
console.log(new Date().getTime() - now)
}
函数内部错处,返回的promise状态为rejected
async function asyncfunc(){
console.log(err)
}
async函数返回的Promise只有函数内部中await后的异步事件执行完后,才会改变,除非中途return或者出错
(async function() {
await new Promise((resolve, reject) => {
console.log("第一个await")
resolve()
})
await new Promise((resolve, reject) => {
console.log("第二个await")
resolve()
})
await new Promise((resolve, reject) => {
console.log("第三个await")
resolve()
})
})().then(info=>{console.log("触发then")})
(async function() {
await new Promise((resolve, reject) => {
console.log("第一个await")
resolve()
})
return "执行return"
await new Promise((resolve, reject) => {
console.log("第二个await")
resolve()
})
await new Promise((resolve, reject) => {
console.log("第三个await")
resolve()
})
})().then(info=>{console.log("触发then")})
(async function() {
await new Promise((resolve, reject) => {
console.log("第一个await")
resolve()
})
throw new Error("出错了")
await new Promise((resolve, reject) => {
console.log("第二个await")
resolve()
})
await new Promise((resolve, reject) => {
console.log("第三个await")
resolve()
})
})()
await后的Promise状态变为rejected时,会被catch接收到
(async function() {
await new Promise((resolve, reject) => {
reject("状态变为rejected")
})
})().catch(info => {
console.log(info)
})
任意一个await后的Promise函数变为rejecte,async函数的执行就会中断,若想继续执行,可使用try{}catch(e){}捕获
(async function() {
await new Promise((resolve, reject) => {
reject("状态变为rejected")
})
await new Promise((resolve, reject) => {
console.log("第二个await")
resolve()
})
})().catch(info => {
console.log(info)
})
(async function() {
try {
await new Promise((resolve, reject) => {
reject("状态变为rejected")
})
} catch (err) {
console.log("捕获" + err)
}
await new Promise((resolve, reject) => {
console.log("第二个await")
resolve()
})
})().catch(info => {
console.log(info)
})
另一种方法是将await后面的Promise添加catch
(async function() {
await new Promise((resolve, reject) => {
reject("状态变为rejected")
}).catch(info => {
console.log("捕获" + info)
})
await new Promise((resolve, reject) => {
console.log("第二个await")
resolve()
})
})().catch(info => {
console.log(info)
})
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。