当前位置:网站首页>Es6中Promise的使用
Es6中Promise的使用
2022-07-07 02:51:00 【這次我一定要贏】
一.Promise是什麼?
Promise是一個構造函數,總共有三種狀態 ,成功(fulfiled),失敗(reject),等待(pending), 裏面有兩個參數resolve和reject。
代碼:
const p1 = new Promise((resolve, reject) => {
})
二.Promise的api方法
1.then拿到成功之後狀態的值。
2.catch捕獲失敗狀態的值。
三.Promise用來幹什麼的?
來解决异步的問題,通常用到請求接口上。
(1)返回的是一個成功(fulfiled)的狀態
代碼:
const p1 = new Promise((resolve, reject) => {
resolve('成功的狀態')
})
console.log(p1);
p1.then(res => {
console.log(res, '拿到接口返回的成功值');
})
成功的狀態:
(2)返回的是一個失敗(reject)的狀態。
代碼:
const p1 = new Promise((resolve, reject) => {
reject('失敗的狀態')
})
console.log(p1);
p1.then(res => {
console.log(res, '拿到接口返回的失敗值');
})
失敗的狀態:
結論:
then是拿不到失敗狀態reject的值的。
這個時候我們來試試.catch
修改代碼:
const p1 = new Promise((resolve, reject) => {
reject('失敗的狀態')
})
console.log(p1);
p1.catch(res => {
console.log(res, '拿到接口返回的成功值');
})
可以捕獲。
(3) 等待(pending)的狀態。
代碼:
const p1 = new Promise((resolve, reject) => {
})
console.log(p1);
等待的狀態:
(4)關聯到實際api接口的調用
如:
1.用mockfast模擬一個接口
2.請求例子
<template>
<div class="">
<button @click="fn">發送get請求</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){return{
}},
name: '',
methods: {
fn(){
// alert('11111111')
axios({
method:'GET',
url:"https://www.fastmock.site/mock/f9834bca1c0604895ec164037a0590c6/api/test",
}).then(res=>console.log(res))
}
},
}
</script>
返回的結果:
請求失敗的時候用.catch進行捕獲,後端也會返回數據給前端。
如:
401 權限不够
404 參數錯誤
500 服務器錯誤 等
這個時候我們需要使用.catch進行捕獲。
四.實際應用
(1)請求接口的方式也是一個异步的强求
<template>
<div class="">
<button @click="fn">發送get請求</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){return{
}},
name: '',
methods: {
fn(){
// alert('11111111')
const p1= axios({
method:'get',
url:"https://www.fastmock.site/mock/f9834bca1c0604895ec164037a0590c6/api/test",
})
console.log(p1,111111111111111111);
}
},
}
</script>
所以我們在平常的開發中可以用then或者catch來對接口的數據進行捕獲。
(2).then和.catch一起使用
<template>
<div class="">
<button @click="fn">發送get請求</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){return{
}},
name: '',
methods: {
fn(){
// alert('11111111')
axios({
method:'get',
url:"https://www.fastmock.site/mock/f9834bca1c0604895ec164037a0590c6/api/test",
}).then(res=>console.log(res)).catch(reject=>console.log(reject))
}
},
}
</script>
五.替代方案async await
用Promise解决异步編程固然是沒有問題的,如果要發送很多的請求呢?
請看下面的代碼:
let a1 = new Promise((resolve, reject) => {
resolve('吃飯')
}).then(res => {
alert(res)
return new Promise((resolve, reject) => {
resolve('睡覺')
})
}).then(res => {
alert(res)
return new Promise((resolve, reject) => {
resolve('打豆豆')
})
}).then(res => alert(res))
如果是多個Promise看起來是不是非常的冗餘。
解决的方案:
async和await
<SCript>
let a1 = new Promise((resolve) => {
resolve('吃飯')
})
let a2 = new Promise((resolve) => {
resolve('睡覺')
})
let a3 = new Promise((resolve) => {
resolve('打豆豆')
})
async function fn() {
const res1 = await a1
console.log(res1);
const res2 = await a2
console.log(res2);
const res3 = await a3
console.log(res3);
}
fn()
</SCript>
它的用法:
在最近一級的函數前面加上async
後面加上await進行接收就可以了
打印出的結果:
對比上面的結果是不是更加清晰一點。
六.用async修飾的函數是异步函數嗎?
看如下代碼:
async function fn() {
console.log(123);
}
console.log(fn());
打印出的結果:
是一個Promise對象,他代錶只是一種狀態。
證明裏面不是异步
代碼:
async function fn() {
console.log(123);
}
console.log(fn());
console.log(456);
如果這個函數是异步執行的輸出的結果是 456 123
而實際的結果是:
所以它不代錶的只是Promise的一種狀態。
如果裏面加上await呢?
代碼:
<SCript>
async function fn() {
await console.log(123);
}
console.log(fn());
console.log(456);
</SCript>
得出結論
await後面的代碼都是异步執行的。
綜上所述:
1.用async修飾的函數裏面並不是异步去執行的,只是變成Promise的一種狀態。
2.在await後面的都是异步去執行的。
七.如何去中斷一個Promise
拋出一個Pending的狀態就可以了
代碼:
new Promise((resolve, reject) => {
resolve(2)
}).then(res => {
// 中斷
throw new Promise((resolve, reject) => {
})
return new Promise((resolve, reject) => {
resolve(3)
})
}).then(res => console.log(res))
八.Promise擴展api
(1)Promise.race
代碼:
const a1 =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(20)
}, 2000);
})
const a2 =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(100)
}, 1000);
})
const a3 =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(30)
}, 3000);
})
const p1 = Promise.race([a1, a2, a3]).then(res => alert(res))
誰用的時間最短就執行誰。
結果肯定執行100。
中途有reject也是一樣的,不管成功失敗誰的時間短。
const a1 =
new Promise((resolve, reject) => {
setTimeout(() => {
reject(20)
}, 2000);
})
const a2 =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(100)
}, 1000);
})
const a3 =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(30)
}, 3000);
})
const p1 = Promise.race([a1, a2, a3]).then(res => alert(res), err => alert(err))
(2)Promise.all
相比於賽跑機制這個是一起去執行的。
const a1 = Promise.resolve(10)
const a2 = Promise.resolve(20)
const a3 = Promise.reject(30)
const p1 = Promise.all([a1, a2, a3]).then(res => console.log(res), err =>
console.log(err))
用[]包裹起來,等裏面的執行完畢在拿到相應的實例
如果中途有錯誤會立馬進行停止。
這個可以在發送多個异步請求的時候使用。發送前有個loading加載的效果。
等异步發送完畢後加載結束。
注意這個和异步的時間沒有關系,和包裹的循序有關系。
const a1 = Promise.resolve(10)
const a2 = Promise.resolve(20)
const a3 = Promise.resolve(30)
const p1 = Promise.all([a2, a1, a3]).then(res => console.log(res), err => console.log(err))
輸出的結果:
[10,20,30]
九.Promise.resolve和Promise.reject
Promise.resolve(2).then(res => console.log(res))
Promise.reject(3).catch(reject => console.log(reject))
它的等價:
Promise.resolve(2).then(res => console.log(res))
new Promise((resolve, reject) => {
resolve(2)
})
Promise.reject(3).then(reject=> console.log(reject))
new Promise((resolve, reject) => {
reject(3)
})
边栏推荐
猜你喜欢
Pioneer of Web3: virtual human
Niuke programming problem -- double pointer of 101 must be brushed
Unity使用MaskableGraphic画一条带箭头的线
Redis introduction complete tutorial: client case analysis
MySQL提升大量数据查询效率的优化神器
普通测试年薪15w,测试开发年薪30w+,二者差距在哪?
HAVE FUN | “飞船计划”活动最新进展
记一次JAP查询导致OOM的问题分析
AWS学习笔记(一)
慧通编程入门课程 - 2A闯关
随机推荐
Derivative, partial derivative, directional derivative
Ali yunyili: how does yunyuansheng solve the problem of reducing costs and improving efficiency?
How to design interface test cases? Teach you a few tips to draft easily
Redis入门完整教程:RDB持久化
左程云 递归+动态规划
How to write test cases for test coupons?
Niuke programming problem -- double pointer of 101 must be brushed
AWS learning notes (I)
Code line breaking problem of untiy text box
Convert widerperson dataset to Yolo format
What management points should be paid attention to when implementing MES management system
Statistics of radar data in nuscenes data set
【2022国赛模拟】多边形——计算几何、二分答案、倍增
Contribution of Writing Series
Hash table and full comments
Redis getting started complete tutorial: common exceptions on the client
Fundamentals of process management
STM32 project -- Topic sharing (part)
CDB PDB 用户权限管理
NuScenes数据集关于Radar数据的统计