我在其他js页面中调用app.js下的squareSupport方法无法获取返回值。但是的确执行了squareSupport方法。我看网上说是因为异步原因,于是我学习了一下promise,但是我发现用了promise还是不行,请问大佬们是我的promise用法不对吗?还是js代码写的有问题?
var supportResult = getApp().squareSupport(id);
console.log('supportResult',supportResult);
下面是app.js中的squareSupport方法。
squareSupport(id) {
wx.getStorage({
key: 'squareSupportList',
complete(res) {
var squareSupportList = res.data;
for (var len = squareSupportList.length, i = len; i >= 0; i--) {
if (squareSupportList[i] == id) {
return 0;
}
}
const promise=new Promise((resolve,reject)=>{
//无该记录返回
wx.request({
header: { "Content-Type": "application/x-www-form-urlencoded" },
url: 'http://localhost:8080/ASchoolCircle/performs/square/support',
data:{
id:id
},
success(res) {
resolve(res);
},
fail(err) {
reject(err);
}
});
});
promise.then(res=>{
console.log(res);
//成功 将记录载入缓存,返回1
if (res.data.msg == 'SUCCESS') {
squareSupportList.push(id);
wx.setStorage({
data: squareSupportList,
key: 'squareSupportList'
});
return 1;
} else {
return -1;
}
},
err=>{
//失败 返回-1
wx.showToast({
title: '网络异常,点赞失败!',
icon: 'none'
});
return -1;
});
}
})
},
asyns/await (ES8环境) 可以实现:
async function proc1(str1){
lca = await db1.collection(col1).where({field1: str1}).get()
return {result: lca.data}
}
另:建议把该函数放在一个公用文件内来给其他文件调用(require)。另外,这里的同步问题的确复杂,还不如把此段代码复制到需要的 js 文件内来得简单明了。
感谢您的建议,我去试试
squareSupport(id) {
wx.getStorage({
key: 'squareSupportList',
complete(res) {
var squareSupportList = res.data;
for (var len = squareSupportList.length, i = len; i >= 0; i--) {
if (squareSupportList[i] == id) {
return 0;
}
}
return new Promise((resolve, reject)=>{
//无该记录返回
wx.request({
header: { "Content-Type": "application/x-www-form-urlencoded" },
url: 'http://localhost:8080/ASchoolCircle/performs/square/support',
data:{
id:id
},
success(res) {
resolve(res);
},
fail(err) {
reject(err);
}
});
});
promise.then(res=>{
console.log(res);
//成功 将记录载入缓存,返回1
if (res.data.msg == 'SUCCESS') {
squareSupportList.push(id);
wx.setStorage({
data: squareSupportList,
key: 'squareSupportList'
});
return 1;
} else {
return -1;
}
},
err=>{
//失败 返回-1
wx.showToast({
title: '网络异常,点赞失败!',
icon: 'none'
});
return -1;
});
}
})
},
还是不行QAQ
谢谢
同问,体验极差