async和await

296 阅读1分钟

一、async

async关键字,表示函数内可能会有异步操作,这样的函数,总是返回一个Promise,具体情况如下:

  1. 没有显式return,相当于return Promise.resolve(undefined);
  2. return非Promise的数据data,相当于return Promise.resolve(data);
  3. return Promise, 会得到Promise对象本身
async function helloAsync(){
  	return "helloAsync";
  }
  helloAsync().then(v=>{
     console.log(v);//"helloAsync"
  })

二、await

await关键字不能单独使用,是需要使用在async方法中。 await字面意思是"等待",那它是在等什么呢? 如果它等到的不是一个 Promise 对象,那 await 表达式的运算结果就是它等到的东西。 如果它等到的是一个 Promise 对象,await 就忙起来了,它会阻塞后面的代码,等着 Promise 对象 resolve,然后得到 resolve 的值,作为 await 表达式的运算结果。

我们知道Promise对象有两种状态,除了resolved,还有rejected,我们来看下如果promise对象变为rejected,会如何处理。

function testAwait(){
  	return Promise.reject("error");
 }
  async function helloAsync(){
  	await testAwait();
  	console.log("helloAsync");//没有打印
  }
  helloAsync().then(v=>{
      console.log(v);
  }).catch(e=>{
     console.log(e);//"error"
  });

从执行结果看,返回reject状态被外层的catch捕获到,然后终止了后面的执行。

但是在有些情况下,出错后是希望继续执行,而不是中断。对于这种情况可以采用tcy...catch在函数内部捕获异常。

function testAwait(){
  		return Promise.reject("error");
  	}
  async function helloAsync(){
  	try{
       await testAwait();
  	}catch(e){
  		console.log("this error:"+e)//this error:error
  	} 	
  	console.log("helloAsync");//helloAsync
  }
  helloAsync().then(v=>{
  }).catch(e=>{
     console.log(e);//没有打印
  });

异常被try...catch捕获后,继续执行下面的代码,没有导致中断。