根本应用
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) })