当前位置:网站首页>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)
})边栏推荐
- 普通测试年薪15w,测试开发年薪30w+,二者差距在哪?
- Detailed explanation of 19 dimensional integrated navigation module sinsgps in psins (filtering part)
- C language exercises_ one
- [Mori city] random talk on GIS data (II)
- Read fast RCNN in one article
- Redis入门完整教程:客户端案例分析
- The so-called consumer Internet only matches and connects industry information, and does not change the industry itself
- 你不可不知道的Selenium 8种元素定位方法,简单且实用
- MySQL
- Redis入门完整教程:复制配置
猜你喜欢

Apifox,你的API接口文档卷成这样了吗?

How to write test cases for test coupons?

服装企业部署MES管理系统的五个原因

Electrical engineering and automation

Compress JS code with terser

dotConnect for DB2数据提供者

【Socket】①Socket技术概述

HAVE FUN | “飞船计划”活动最新进展

Have fun | latest progress of "spacecraft program" activities

Linear list --- circular linked list
随机推荐
一本揭秘字节万台节点ClickHouse背后技术实现的白皮书来了!
PSINS中19维组合导航模块sinsgps详解(初始赋值部分)
用全连接+softmax对图片的feature进行分类
Code line breaking problem of untiy text box
Compress JS code with terser
慧通编程入门课程 - 2A闯关
Django数据库(SQlite)基本入门使用教程
QT common Concepts-1
INS/GPS组合导航类型简介
The 8 element positioning methods of selenium that you have to know are simple and practical
Redis introduction complete tutorial: client case analysis
What are the applications and benefits of MES management system
Planning and design of double click hot standby layer 2 network based on ENSP firewall
NuScenes数据集关于Radar数据的统计
Remember the problem analysis of oom caused by a Jap query
Statistics of radar data in nuscenes data set
CSDN 夏令营课程 项目分析
从控制理论的角度谈数据分析
MySQL
Pioneer of Web3: virtual human