async+await的个人理解

async+await是es7提出来的概念,它也是为了解决回调地狱的问题,它只是一种语法糖,从本质上讲,await函数仍然是promise,

值得注意的是,asyncawait必须要一起使用。

用法:首先在 function 前面加 async 用来说明这个函数是一个异步函数

然后在async里面写await

例如:

async function a(y){
    let sum = await b(3,4)
    let c= sum+y;
    console.log(c)
}
function b (x,y){
    return x+y;
}
a(10)

上面的例子中:sum变量是等着b()这个函数执行完毕才有值的 ,其实await和promise中的 .then()差不多

使用promises,异步函数有两个可能的返回值:已解析的值和被拒绝的值。我们可以.then()用于正常情况,.catch()用于特殊情况。但是,async/await错误处理可能会很棘手。

try…catch

最标准的(我推荐的)方法是使用try...catch语句。当一个await调用时,任何被拒绝的值都将作为异常抛出。

例如:

async function a(y){
 try{
  let a = await b(3,4)
    let c= a+y;
    console.log(c)
}catch(err){
	console.log(err);
 }
}
function b (x,y){
    return x+y;
}
a(10,)

猜你喜欢

转载自blog.csdn.net/weixin_41615439/article/details/88896675