es6 async 总结

//1 async 返回一个promise对象因此能够经过.then来调用

async function test1() {
return "测试数据"
}
test1().then((e)=>{
console.log(e) // 测试数据
});


//2 async 里面若是遇到 return 会直接返回传到then里面,不执行后面代码模块了

async function test2() {
return "测试数据2";
console.log(1) //不会执行
}
test2().then((e)=>{
console.log(e) // 测试数据
});


//3 await 后面函数若是不是promise对象是个普通函数,而普通函数里面包含一个异步,await不会等这个异步执行完。

function test3(){
setTimeout(function () {
console.log(1)
},1000)
}
async function test_3() {
await test3();
console.log(2)
}
test_3() //2 1 先输出2 后输出1


//4 用try语句能够防止await异步失败影响后面代码执行。

function test_4a() {
return new Promise((resolve,reject)=>{
console.log(1);
resolve(1)
})
}
function test_4b() {
return new Promise((resolve,reject)=>{
console.log(2);
reject()
})
}
async function test4() {
try {
await test_4b();
await test_4a();
} catch (e) {

}

}
test4() // 1
相关文章
相关标签/搜索