当前位置:网站首页>项目中new Promise和async、await中的使用,以及promise.all在项目中的实际应用
项目中new Promise和async、await中的使用,以及promise.all在项目中的实际应用
2022-07-25 19:40:00 【小刘先生很努力】
我们先了解一下 async 和await 以及promiss
什么是async/await
async/await是写异步代码的新方式,它是generator的语法糖,以前的方法有回调函数和 Promise。
async/await是基于Promise实现的,它不能用于普通的回调函数。
async/await与Promise一样,是非阻塞的。
async/await使得异步代码看起来像同步代码,这正是它的魔力所在。
什么是Promise
Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。
所谓promise,简单说就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果。从语法上说,Promise 是一个对象,从它可以获取异步操作的消息。
区别
- 函数前面多了一个async关键字。await关键字只能用于async定于的函数内。async函数会隐式地返回一个Promise,该promise的resolve值就是return的值。
- await的必须在异步函数中使用;其中await有限制(不允许出现在箭头函数中;不允许出现在同步函数声明中;不允许出现在同步函数表达式中;如果在同步函数中使用await就会抛出SyntaxError。)
用async/await更好
- 使用async函数可以让代码简洁很多,不需要想Promise一样需要then,不需要写匿名函数处理Promise的resolve的值,也不需要定义多余的data变量,还避免了嵌套代码。
- async/await 让 try/catch可以同时处理同步和异步的错误。在下面的示例中,try/catch不能处理JSON.parse的错误,因为它在Promise中,我们需要使用.catch,这样的错误会显得代码非常的冗余。
例子:
async function update(data) {
await this.changeListChOrgInfo();//当changeListChOrgInfo()执行完成之后,才执行下方this.iscompany的操作
this.iscompany = true;
},
function changeListChOrgInfo({commit}) {//返回一个Promise对象
return new Promise((resolve, reject) => {
changelistChOrgInfo({})//一个ajax请求
.then(response => {
if(!response.body){
}
else{
}
resolve()
})
.catch(error => {
console.log(error);
reject();
});
})
}
项目中假设需求:在实际项目的开发应用中我们需要先执行前两个方法,用两个方法返回的数据作为参数去执行第三个方法
这时候我们就需要使用new promise、resolve、promise.all等方法。
实际中,可根据项目实际情况进行变通
方法一:假设我们要获取账户信息,肯定是一个方法,写在 methods中
// 账户信息获取
getAccount(){
return new Promise((resolve,reject)=>{
this.$axios.post(CONFIG.httphost() + '/user/queryUser',{
st:1,
limit:0
}).then(resp =>{
let res = resp.data; // 返回数据
let code = res.code; // 数据code码,一般为200
if(!code){
this.accountList = res.data;
//值得注意的是这里,new promise的方法正确请求是要resolve出来,才能继续向下执行
resolve();
}else{失败的话,返回什么或者提示啥,看着写呗}
})
})
},
方法二:
// 获取单位
getDW() {
return new Promise((resolve,reject)=>{
this.$axios.post(CONFIG.httphost() + "/MessageShowController/showDwMessage", {
st: 1,
limit: 0
}).then((resp) => {
let res = resp.data;
let code = res.code;
if (!code) {
this.dwList = res.data;
resolve()
} else {
this.giveMsg("请求数据失败");
}
});
})
},
方法三: 拿到第一第二个再去获取第三个
// 获取数据
getData() {
Promise.all([
this.getAccount(), // 第一个
this.getDW(), // 第二个
]).then(res=>{ // 请求成功获取第三个接口
//此处的请求方法根据实际封装变通
this.$axios.post(CONFIG.httphost() + "/MessageCollectorController/showBmJurisdiction", {
dw_id: self.dw_id, // 接收的参数
userid:this.userid, // 接收的参数
})
.then((resp) => { // 赋值
let res = resp.data;
let code = res.code;
if (!code) {
this.$nextTick(() => {
this.getRoleMenu(res.data);
});
}else{可写可不写,看需求。}
})
.catch((err) => {
});
})
}
有机会咱们在沟通沟通类,欢迎指正。谢谢谢谢
边栏推荐
- Binarysearch basic binary search
- 由一个蓝桥杯基础题报时助手而引出的常见误区
- 国内常见php的CMS建站系统情况分析
- Code sharing of social chat platform developed by dating website (III)
- TypeError: ‘str‘ object is not callable的错误原因
- 浅谈接口加密
- How to be a self disciplined person?
- Scala foundation [set 01]
- what is qml in qt
- Talk about 11 tips for interface performance optimization
猜你喜欢

Skiing mobile H5 game source code download

Concept of IP address

How to ensure the consistency of double write between database and cache?

某公司网络设计与规划

微信小程序开发之网络数据请求

Js分页插件支持表格、列表、文本、图像

Eve - 0day Threat Intelligence

重磅!《几何深度学习》新书发布,帝国理工/DeepMind等图ML大牛共同撰写,160页pdf阐述几何DL基础原理和统一框架

Dynamic implementation of wechat applet 27 progress bar and static construction of search box and hot search list

A high efficiency 0-delay 0-copy QT player scheme based on Hisilicon 3559
随机推荐
GBASE 8s UDR内存管理_03_mi_realloc
How many lines of code is appropriate for a function? Clean Code
University of California | feasible confrontation robust reinforcement learning for unspecified environments
伺服驱动器在机器人上的研究与应用
由一个蓝桥杯基础题报时助手而引出的常见误区
Flutter tips: optimizing the buildcontext you use
Solve the problem that the win10 account has no administrator rights
【刷题记录】21. 合并两个有序链表
Selenium运行慢 - 通过设置selenium加载策略加快运行速度
Skiing mobile H5 game source code download
给容器添加3d效果的副标题
Dynamic implementation of wechat applet 27 progress bar and static construction of search box and hot search list
What is idealism
Code sharing of social chat platform developed by dating website (III)
[wp]ctfshow-web入门信息搜集
Gbase 8s UDR memory management_ 03_ mi_ realloc
Sccm2012r2 network deployment reinstallation system
VMware virtual machine download, installation and use tutorial
重磅!《几何深度学习》新书发布,帝国理工/DeepMind等图ML大牛共同撰写,160页pdf阐述几何DL基础原理和统一框架
Imeta | sangerbox: interactive integrated clinical information analysis platform