当前位置:网站首页>项目中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) => {
});
})
}
有机会咱们在沟通沟通类,欢迎指正。谢谢谢谢
边栏推荐
- Research and application of servo driver in robot
- 微信小程序开发之全局配置与页面配置
- Network packet multi-layer transmission demonstration
- Authorized wireless communication standard
- An idea of solving div adapting to screen
- Beihang and other "deep learning event extraction" literature review paper, 27 page PDF describes the current trend
- GBASE 8s UDR内存管理_02_mi_dalloc
- Selenium runs slowly - speed up by setting selenium load policy
- Mutual conversion of camera internal parameter matrix K and FOV
- Gbase 8s UDR memory management_ 01_ mi_ alloc
猜你喜欢

Small program completion work wechat campus maintenance application small program graduation design finished product (2) small program function

Wechat campus maintenance and repair applet graduation design finished product (7) Interim inspection report

Imperial cms7.5 imitation "question and answer library" question and answer learning platform website source code with mobile version

Empire CMS whole station | mobile number /qq lianghao mall source code | suitable for mobile terminal

Openresty Lua resty mlcache multi-level cache

【HDLBits 刷题】Verilog Language(3)Modules: Hierarchy 部分

Wechat campus maintenance and repair applet graduation design finished product of applet completion work (4) opening report

Ml programming skills:

微信小程序 28 热搜榜的完善①

虹科分享|如何解决勒索软件安全漏洞
随机推荐
【好书推荐】-- 《以太网权威指南》(第2版)
Legal mix of collations for operation 'Union' (bug record)
ML的编程技巧:
微信小程序 26 播放音乐页的完善②
Old wine in new bottles -- sample analysis of recent apt32 (sea Lotus) organizational attacks
Grid layout frequently asked interview questions
Code sharing of social chat platform developed by dating website (III)
解决Win10账户没有了管理员权限
Day7:有序二叉树(二叉搜索树)
帝国CMS7.5仿《问答库》题库问答学习平台网站源码 带手机版
what is qml in qt
什么是唯心主义
Imperial cms7.5 imitation "question and answer library" question and answer learning platform website source code with mobile version
Monitor MySQL based on MySQL exporter
Use of swift basic codable (jsonencoder jsondecoder)
On interface encryption
Wechat campus maintenance and repair applet graduation design finished product (5) assignment of applet completion work
Common misunderstandings caused by a time reporting assistant of Blue Bridge Cup basic questions
Basic practice of Blue Bridge Cup - shape retrieval of matrix (C language)
微信小程序开发之全局配置与页面配置