一,async的使用
async
可以作用在任何方法前, 返回值是一个Promise对象(回调函数也可以使用async)
函数内部return的返回值, 会成为then回调函数的参数
async作用的方法,如果内部出现报错,可以被promise的catch方法捕获
常规使用,一般都会通过try catch进行有可能报错的代码处理
//函数内部return的返回值, 会成为then回调函数的参数
var a1=async()=>{
return 111
}
a1().then(res=>{
console.log(res)
})
//async作用的方法,如果内部出现报错,可以被promise的catch方法捕获
function fn(){
return new Promise((reslove,reject)=>{
throw new Error(111)//手写的错误信息
setTimeout(()=>{
console.log(3);
resolve(666)//成功后执行
},3000)
})
}
(async function(){
console.log(1);
//错误捕获
try{
await fn()
}catch(e){
console.log(e)
}
console.log(2)
})().catch(err=>{
console.log(err)
})
//运行结果
//1
//Error: 11111
// at 1.html:25
// at new Promise (<anonymous>)
// at f (1.html:24)
// at 1.html:35
// at 1.html:40
//2
function fn1() {
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(1)
console.log('1秒');
},1000)
})
}
function fn2() {
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(2)
console.log('2秒');
},2000)
})
}
function fn3() {
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(3)
console.log('3秒');
},3000)
})
}
(async function() {
var a = fn1()
var b = fn2()
var c = fn3()
await a // 1
await b // 2
await c // 3
console.log(a,b,c);
})()
二,await
await
await只能作用在async修饰的方法中,不能单独使用,如果使用报错:await is only valid in async functions and the top level bodies of modules
await是会阻塞代码执行
正常情况 await后面跟着一个Promise对象; 返回的是Promise对象的成功后结果; 如果是一个普 通 值,那么会直接返回这个值
reject的返回 await没有办法进行捕获(使用try catch进行捕获)
{
let p1 = ()=>{
return new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve("hello world")
},3000)
})
}
async function fn3(){
console.time("step3_1");
let res = await p1();
console.timeEnd("step3_1");
}
fn3();
}