index 调用utils函数做数据库查询,返回值为V {}为什么,如何解决。
index.js
const utils = require('../../utils/utils')
var event = {databaseName: 'aaa',targetData: 'openId',content: this.data.openId}
const temp = utils.getRecord(event)
consolse.log(temp)
utils
第一种
<function getRecord(event) {
const {
databaseName,
databaseId,
targetData,
content,
} = event
return db.collection(databaseName).where({
[targetData]: content
}).get()
}>
第二种
async function getRecord(event){
return new Promise((resolve,reject)=>{
db.collection(databaseName).where({
[targetData]: content
}).get().then(res=>{
resolve (res)
})
})
}
在utils里输出结果是正常的,但是到index输出结果却是
想得到查询到的信息。
2个都是返回promise,所以打印的对象是Promise没问题,需要加then获取数据
const utils = require('../../utils/utils')
var event = {databaseName: 'aaa',targetData: 'openId',content: this.data.openId}
utils.getRecord(event).then(res=>{console.log(res)})
第二种可以给index.js获取数据的函数加上async,用await可以获取数据
Page({
onLoad:async function (options) {
var d ={
databaseName:'test',
targetData:'_id',
content:'5b049cc861de71d304c319cf3874e1f4',
}
var d=await utils.getRecord(d)
console.log(d)
}
})
你返回的是Promise对象,要获取值需要temp.then(res => console.log(res))
云函数库 操作权限改了吗?
操作云数据库应该是 promise封装的数据处理,
解决方案
const utils = require('../../utils/utils')
async 函数 (){
var event = {databaseName: 'aaa',targetData: 'openId',content: this.data.openId}
const temp = await utils.getRecord(event)
consolse.log(temp)
}
const utils = require('../../utils/utils')
var event = {databaseName: 'aaa',targetData: 'openId',content: this.data.openId}
utils.getRecord(event).then(res=>{
console.log(res)
})
}
第一种方法,getRecord中添加回掉方法
utils修改
```typescript
async function getRecord(event, callback){
return new Promise((resolve,reject)=>{
db.collection(databaseName).where({
[targetData]: content
}).get().then(res=>{
resolve (res)
callback(res)
})
})
}
index修改
```javascript
utils.getRecord(event, (temp) => {console.log(temp)})
第二种方法 index 中修改一下
const temp = await utils.getRecord(event)
utils 中修改一下
```typescript
async function getRecord(event){
return await new Promise((resolve,reject)=>{
db.collection(databaseName).where({
[targetData]: content
}).get().then(res=>{
resolve (res)
})
})
}
```