async函数返回的是一个Promise,可以进行Promise的相关操做,函数内部返回的结果会成为then方法回调函数的参数promise
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状态为rejectedasync
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接收到spa
(async function() { await new Promise((resolve, reject) => { reject("状态变为rejected") }) })().catch(info => { console.log(info) })
任意一个await后的Promise函数变为rejecte,async函数的执行就会中断,若想继续执行,可以使用try{}catch(e){}捕获3d
(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添加catchcode
(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) })