提示:promise,async →await,then→catch,try→catch 使用简介
文章目录
- 前言
- 一、Promise
- 二、promise then/catch
- 三、promise async/await try/catch
- 总结
前言
需求:promise,async →await,then→catch,try→catch 使用简介
一、Promise
w3c-school-promise介绍
Promise 是一个 ECMAScript 6 提供的类,目的是更加优雅地书写复杂的异步任务。
//新建一个 Promise 对象
new Promise(function (resolve, reject) {// 需要执行的任务代码块//resolve promise里代码全部执行成功时调用//reject promise里代码出现异常时调用
});
示例:
<!DOCTYPE html>
<html lang="en">
<body><div style="text-align: center;">promise</div><script>let num = 3;new Promise((resolve,reject)=>{setTimeout(()=>{if(num>5){resolve({msg:`2秒后 num=${num}大于5 执行的resolve`})}else{reject({msg:`2秒后 num=${num}小于等于5 执行的reject`});}},1000);});</script>
</body>
</html>
因为没有捕获异常,所以浏览器把异常抛出来了
二、promise then/catch
then:执行resolve后,进入then
catch :执行reject后,进入catch
1、执行resolve后,进入then
<!DOCTYPE html>
<html lang="en">
<body><div style="text-align: center;">promise</div><div style="text-align: center;">then catch</div><script>let num = 6;new Promise((resolve,reject)=>{setTimeout(()=>{if(num>5){resolve({msg:`2秒后 num=${num}大于5 执行的resolve`})}else{reject({msg:`2秒后 num=${num}小于等于5 执行的reject`});}},1000);}).then(data=>{console.log(data,'then success')}).catch(err=>{console.log(err,'catch err')})</script>
</body>
</html>
2、执行reject后,进入catch
<!DOCTYPE html>
<html lang="en">
<body><div style="text-align: center;">promise</div><div style="text-align: center;">then catch</div><script>let num = 3;new Promise((resolve,reject)=>{setTimeout(()=>{if(num>5){resolve({msg:`2秒后 num=${num}大于5 执行的resolve`})}else{reject({msg:`2秒后 num=${num}小于等于5 执行的reject`});}},1000);}).then(data=>{console.log(data,'then success')}).catch(err=>{console.log(err,'catch err')})</script>
</body>
</html>
三、promise async/await try/catch
try:执行resolve后,进入try
catch :执行reject后,进入catch
1、try接收resolve
//只有async函数的内部,才可以使用await函数
//await 把函数返回的PromiseObject转化成普通object
<!DOCTYPE html>
<html lang="en">
<body><div style="text-align: center;">promise</div><div style="text-align: center;">try catch</div><script>function testPromise(num){return new Promise((resolve,reject)=>{setTimeout(()=>{if(num>5){resolve({msg:`2秒后 num=${num}大于5 执行的resolve`})}else{reject({msg:`2秒后 num=${num}小于等于5 执行的reject`});}},1000);})}async function testTry(num){try{const data = await testPromise(num);console.log(data,'try success');}catch(err){console.log(err,'catch err');}}testTry(6)</script>
</body>
</html>
2、catch接收reject
<!DOCTYPE html>
<html lang="en">
<body><div style="text-align: center;">promise</div><div style="text-align: center;">try catch</div><script>function testPromise(num){return new Promise((resolve,reject)=>{setTimeout(()=>{if(num>5){resolve({msg:`2秒后 num=${num}大于5 执行的resolve`})}else{reject({msg:`2秒后 num=${num}小于等于5 执行的reject`});}},1000);})}async function testTry(num){try{const data = await testPromise(num);console.log(data,'try success');}catch(err){console.log(err,'catch err');}}testTry(3)</script>
</body>
</html>
总结
踩坑路漫漫长@~@