先說結論:這類問題大概率與異步執行有關。
問題表現:
本地調試結果符合預期,上傳代碼關閉本地執行後結果異常
問題定位:
在我的個案中,我是需要用到異步查詢雲數據庫,並根據結果查詢結果返回的,一開始我的代碼如下
const cloud = require('wx-server-sdk')
cloud.init({
// API 調用都保持和雲函數當前所在環境一致
env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
// 雲函數入口函數
exports.main = async (event, context) => {
var canMatch=false;
const wxContext = cloud.getWXContext()
db.collection('relation').where({
shareid: event.shareid
}).get().then(
res=>{
console.log('res is ',res)
if(res.data.length==0){
console.log('check point 2')
db.collection('relation').where({
shareid: event.openid
}).get().then(
res => {
if (res.data.length == 0) {
console.log('check point 3')
canMatch=true //可能沒執行到
console.log('match result',canMatch)
}else{
}
}
)
}else{
}
}
)
return {
canMatch: canMatch
}
問題出在了異步上,最後一行的return和數據庫查詢是異步的,導致可能查詢結果沒出來,還沒執行”canMatch=true“就已經退出函數了,返回默認值false。在本地調試的時候,數據庫查詢結果出來較快,所以結果表現出來與順序執行一樣,所以沒有發現錯誤。在雲端執行時,執行順序與本地不一樣。
解決方法:
使用await即可解決該問題,使得函數在執行與同步執行一致即可
const cloud = require('wx-server-sdk')
cloud.init({
// API 調用都保持和雲函數當前所在環境一致
env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
// 雲函數入口函數
exports.main = async (event, context) => {
var canMatch=false;
const wxContext = cloud.getWXContext()
console.log('shareid is ',event.shareid)
console.log('canMatch def',canMatch)
let a= await db.collection('relation').where({
shareid: event.shareid
}).get()
console.log('a.data',a.data)
if(a.data.length==0){
console.log('check point 2')
let b = await db.collection('relation').where({
shareid: event.openid
}).get()
if (b.data.length == 0) {
console.log('check point 3')
canMatch=true
console.log('match result',canMatch)
}
}
console.log('canMatch is',canMatch)
return {
canMatch: canMatch
}
}