点击按钮触发onScan函数,函数调用扫描二维码这个异步操作后,需要扫描二维码的函数返回结果,可以用Promise来实现。Promise对象状态变为resolved(成功)或rejected(失败),然后将解决(或拒绝)的值作为表达式的结果返回。
scanQrCode: function()
{
return new Promise((resolve, reject) =>
{
uni.scanCode
({
onlyFromCamera: true,
scanType: ['qrCode'],
success: function (res)
{
console.log('条码类型:' + res.scanType);
console.log('条码内容:' + res.result);
resolve(res.result)
},
fail: function()
{
reject('fail')
}
});
});
},
onScan: function()
{
this.scanQrCode().then((arrRtn) =>
{
console.log('arrRtn = ', arrRtn)
})
.catch(error =>
{
console.error('error = ', error);
// 处理错误
})
},
而如果点击按钮后,执行的onScan函数不能立即调用扫描二维码这个异步操作,而是弹出一个选择框(确定和取消),点击确定才能调用扫描二维码,相当于异步函数里调用异步函数。这时候可以用 async/await 结合Promise对象的方式。await是JavaScript中用于等待一个Promise对象执行完成并返回结果的关键字。当在一个使用async修饰的函数中使用await关键字时,它会暂停函数的执行,直到该Promise对象状态变为resolved(成功)或rejected(失败),然后将解决(或拒绝)的值作为表达式的结果返回。
scanQrCode: function()
{
return new Promise((resolve, reject) =>
{
uni.scanCode
({
onlyFromCamera: true,
scanType: ['qrCode'],
success: function (res)
{
console.log('条码类型:' + res.scanType);
console.log('条码内容:' + res.result);
resolve(res.result)
},
fail: function()
{
reject('fail')
}
});
});
},
onScan: function ()
{
let that = this
uni.showModal
({
title: '提示标题',
content: '提示内容',
showCancel: true,
cancelText: '取消',
confirmText: '确定',
success: async (res) =>
{
if (res.confirm)
{
console.log('用户点击确定按钮')
const scanRes = await that.scanQrCode()
console.log('scanRes = ', scanRes)
}
else if (res.cancel)
{
console.log('用户点击取消按钮')
}
}
})
},
上面这种async/await的写法,也可以改用.then()来实现
scanQrCode: function()
{
return new Promise((resolve, reject) =>
{
uni.scanCode
({
onlyFromCamera: true,
scanType: ['qrCode'],
success: function (res)
{
console.log('条码类型:' + res.scanType);
console.log('条码内容:' + res.result);
resolve(res.result)
},
fail: function()
{
reject('fail')
}
});
});
},
onScan: function ()
{
let that = this
uni.showModal
({
title: '提示标题',
content: '提示内容',
showCancel: true,
cancelText: '取消',
confirmText: '确定',
success: (res) =>
{
if (res.confirm)
{
that.scanQrCode().then(scanRes =>
{
console.log('用户点击确定按钮');
console.log('scanRes = ', scanRes);
}).catch(error =>
{
console.error('扫描错误:', error);
});
}
else if (res.cancel)
{
console.log('用户点击取消按钮');
}
}
});
},