当前位置:网站首页>微信小程序异步回调函数恶梦和解决办法
微信小程序异步回调函数恶梦和解决办法
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')边栏推荐
- Good News | AR opens a new model for the textile industry, and ALVA Systems wins another award!
- 使用DBeaver进行mysql数据备份与恢复
- Win Go development kit installation configuration, GoLand configuration
- Centos7 安装postgresql并开启远程访问
- Safety (2)
- 接口测试神器Apifox究竟有多香?
- Project Background Technology Express
- AWR分析报告问题求助:SQL如何可以从哪几个方面优化?
- MySQL - CRUD operations
- "NetEase Internship" Weekly Diary (3)
猜你喜欢
![[Server data recovery] Data recovery case of server Raid5 array mdisk disk offline](/img/08/d693c7e2fff8343b55ff3c1f9317c6.jpg)
[Server data recovery] Data recovery case of server Raid5 array mdisk disk offline

The first time I wrote a programming interview question for Niu Ke: input a string and return the letter with the most occurrences of the string

Handwritten Blog Platform ~ Day Two

【 wheeled odometer 】

LeetCode brush diary: LCP 03. Machine's adventure

2022-07-30 mysql8执行慢SQL-Q17分析

项目场景 with ERRTYPE = cudaError CUDA failure 999 unknown error

Redis Subscription and Redis Stream

FOFAHUB usage test

Win Go development kit installation configuration, GoLand configuration
随机推荐
AWR分析报告问题求助:SQL如何可以从哪几个方面优化?
2023年起,这些地区软考成绩低于45分也能拿证
Remember a gorm transaction and debug to solve mysql deadlock
Rasa 3.x 学习系列- Rasa - Issues 4873 dispatcher.utter_message 学习笔记
欧拉公式的证明
永磁同步电机36问(三)——SVPWM代码实现
字典常用方法
swift项目,sqlcipher3 -&gt; 4,无法打开旧版数据库有办法解决吗
What to study after the PMP exam?The soft exam ahead is waiting for you~
局部敏感哈希:如何在常数时间内搜索Embedding最近邻
Effects of Scraping and Aggregation
The principle and code implementation of intelligent follower robot in the actual combat of innovative projects
字符串常用方法
Pinduoduo leverages the consumer expo to promote the upgrading of domestic agricultural products brands and keep pace with international high-quality agricultural products
cocos中使用async await异步加载资源
机器人领域期刊会议汇总
BI - SQL 丨 WHILE
Nanoprobes Polyhistidine (His-) Tag: Recombinant Protein Detection Protocol
Moonbeam and Project integration of the Galaxy, bring brand-new user experience for the community
Redis Persistence - RDB and AOF