当前位置:网站首页>微信小程序异步回调函数恶梦和解决办法
微信小程序异步回调函数恶梦和解决办法
2022-08-02 02:21:00 【wxgnolux】
问题
先看看下面的代码,是读写取腾讯cos,因为几个对象间是有层次关系的,要读出一个取值然后作为另一个的条件,再去读,依次有几层关系。 按照官方文档,每一次都要放在回调函数里取结果,这样一层一层嵌套起来,可读性非常的差。 而且还有个致命的问题,这些回调函数都是异步处理的,当同一层并依序并列处理时,因为异步原因,没法按代码顺序来执行。
cos.getBucket({
Bucket: Bucket,
Region: Region,
Prefix: preday, // 这里传入列出的文件前缀
},
function (err, data) {
if (data) {
console.log(data)
var count = 0
var len = data.Contents.length
console.log('len', len)
for (var i = 0; i < len; i++) {
var key2 = data.Contents[i].Key;
cos.getObject({
Bucket: Bucket,
Region: Region,
Key: key2,
}, function (err, data) {
count++;
console.log(data)
if (data) {
var obj = JSON.parse(data.Body);
recent = that.data.recent;
var uname = obj.uname
cos.getObject({
Bucket: Bucket,
Region: Region,
Key: uname,
}, function (err, data) {
var obj = JSON.parse(data.Body);
recent.push({
uid: obj.uid,
date_expire: obj.date_expire
});
})
if (count >= len) {
let s1 = new Set(recent);
recent = Array.from(s1);
console.log('array',recent)
that.setData({
recent: recent
});
console.log('recent', that.data.recent,that.data.list)
}
}
});
};
};
}
);
if (that.data.inputValue != '') {
cos.getObject({
Bucket: Bucket,
Region: Region,
Key: that.data.inputValue,
}, function (err, data) {
//console.log(err || data.Body);
if (data) {
var obj = JSON.parse(data.Body);
var uname = obj.uname;
var ary = uname.split('+');
var remark = "";
if (obj.remark) {
remark = obj.remark
};
that.setData({
corpid: ary[0],
agentid: ary[1],
uid: that.data.inputValue,
userid: ary[2],
remark: remark
});
cos.getObject({
Bucket: Bucket,
Region: Region,
Key: uname,
}, function (err, data) {
if (data) {
var obj = JSON.parse(data.Body);
var date_expire = obj.date_expire;
that.setData({
date_expire: date_expire
});
}
});
cos.getBucket({
Bucket: Bucket,
Region: Region,
Prefix: that.data.corpid,
},
function (err, data) {
//console.log(err || data.Contents);
if (data) {
var list = []
var count = 0
var len = data.Contents.length
for (var i = 0; i < len; i++) {
var key2 = data.Contents[i].Key;
cos.getObject({
Bucket: Bucket,
Region: Region,
Key: key2,
}, function (err, data) {
count++;
if (data) {
var obj = JSON.parse(data.Body);
list = that.data.list;
var arr2 = key2.split('+')
list.push({
uid: obj.uid,
date_expire: obj.date_expire
});
console.log(count, len)
if (count >= len) {
let s1 = new Set(list);
list = Array.from(s1);
that.setData({
list: list
})
}
}
});
};
};
}
);
}
});
}; 解决方法
可以使用 Promise 来重新包装一下 COS 的接口如下:这样这些函数就变成同步的方式来调用了。
//get bucket contents from prefix
const getBucket = (Prefix) => {
return new Promise((resolve, reject) => {
cos.getBucket({
Bucket: Bucket,
Region: Region,
Prefix: Prefix,
}, function (err, data) {
if (err) {
//console.log('error', err)
reject(err)
} else {
//console.log('success', data)
resolve(data.Contents)
}
});
});
} //end getBucket
//get object from key
const getObject = (Key) => {
return new Promise((resolve, reject) => {
cos.getObject({
Bucket: Bucket,
Region: Region,
Key: Key,
}, function (err, data) {
if (err) {
//console.log('error2', err)
reject(err)
} else {
//console.log('success2', data)
resolve(data.Body)
}
});
});
} //end getObject
//put object to key
const putObject = (Key, Body) => {
return new Promise((resolve, reject) => {
cos.putObject({
Bucket: Bucket,
Region: Region,
Key: Key,
Body: Body
}, function (err, data) {
if (err) {
reject(err)
} else {
//console.log(data)
resolve(data)
}
});
});
} //end putObject 调用的方式,有几点要求,首先调用的主函数定义前必须加上 async ,其次在调用上面包装好的函数时,要加 await. 如下:
async Test(e){
let rlt1 = await getObject('keyname')
rlt1 = JSON.parse(rlt1)
},扩展
另外 微信小程序的库里本身带的很多函数就是支持这种调用的方式,以支持同步执行的方式如所示:
// wx.showModal 官方文档中的调用方式,这种是异步的方式
// 执行会发现 最后面的 log('3')会先输出,log('2')反而后输出。
console.log('1')
wx.showModal({
title: '提示',
content: '这是一个模态弹窗',
success(res) {
if (res.confirm) {
console.log('用户点击确定')
console.log('2')
} else if (res.cancel) {
console.log('用户点击取消')
console.log('2')
}
}
});
console.log('3')
//可以改成下面的调用方式,就能顺序执行了。
let res = await wx.showModal({
title: '提示',
content: '这是一个模态弹窗'
});
if (res.confirm) {
console.log('用户点击确定')
console.log('2')
} else if (res.cancel) {
console.log('用户点击取消')
console.log('2')
}
console.log('3')边栏推荐
- nacos启动报错,已配置数据库,单机启动
- Power button 1374. Generate each character string is an odd number
- Safety (1)
- 个人博客系统项目测试
- 【ORB_SLAM2】void Frame::AssignFeaturesToGrid()
- BioVendor Human Club Cellular Protein (CC16) Elisa Kit Research Fields
- CodeTon Round 2 D. Magical Array
- 软件测试 接口自动化测试 pytest框架封装 requests库 封装统一请求和多个基础路径处理 接口关联封装 测试用例写在yaml文件中 数据热加载(动态参数) 断言
- Check if IP or port is blocked
- Handwriting a blogging platform ~ the first day
猜你喜欢

Win Go development kit installation configuration, GoLand configuration

2022-07-30 mysql8 executes slow SQL-Q17 analysis

列表常用方法

NAS和私有云盘的区别?1篇文章说清楚

永磁同步电机36问(二)——机械量与电物理量如何转化?

2022 Henan Youth Training League Game (3)

LeetCode brush diary: LCP 03. Machine's adventure

BI-SQL丨WHILE

机器人领域期刊会议汇总
![[Unity entry plan] 2D Game Kit: A preliminary understanding of the composition of 2D games](/img/8a/07ca69c6dcc22757156cb615e241f8.png)
[Unity entry plan] 2D Game Kit: A preliminary understanding of the composition of 2D games
随机推荐
2022-08-01 mysql/stoonedb slow SQL-Q18 analysis
项目场景 with ERRTYPE = cudaError CUDA failure 999 unknown error
2022 NPDP take an examination of how the results?How to query?
NAS和私有云盘的区别?1篇文章说清楚
swift项目,sqlcipher3 -&gt; 4,无法打开旧版数据库有办法解决吗
"NetEase Internship" Weekly Diary (1)
2022-08-01 mysql/stoonedb慢SQL-Q18分析
oracle query scan full table and walk index
libcurl访问url保存为文件的简单示例
51. 数字排列
Unable to log in to the Westward Journey
Reflex WMS Intermediate Series 7: What should I do if I want to cancel the picking of an HD that has finished picking but has not yet been loaded?
2022-08-01 安装mysql监控工具phhMyAdmin
AI目标分割能力,无需绿幕即可实现快速视频抠图
From 2023 onwards, these regions will be able to obtain a certificate with a score lower than 45 in the soft examination.
项目后台技术Express
Use DBeaver for mysql data backup and recovery
BI - SQL 丨 WHILE
The principle and code implementation of intelligent follower robot in the actual combat of innovative projects
JVM调优实战