微信小程序 云函数

定义云函数

  • 创建云函数以后,会自动给出一个基本的框架如下:
const cloud = require('wx-server-sdk')
// 云函数入口函数
exports.main = async (event, context) => {

}
  • 其中,event 是调用云函数是输入的数据,是一个类对象。context 用于获取用户信息,也是一个类对象。如下两个程序是官方文档中的实例:
exports.main = async (event, context) => ({
  sum: event.a + event.b
})
const cloud = require('wx-server-sdk')
exports.main = (event, context) => {
  // 这里获取到的 openId、 appId 和 unionId 是可信的,
  //注意 unionId 仅在满足 unionId 获取条件时返回
  const {OPENID, APPID, UNIONID} = cloud.getWXContext()

  return {
    OPENID,
    APPID,
    UNIONID,
  }
}

云函数的调用

  • 云函数的调用是 wx.cloud.callFunction( Object )
  • 其中 Object 中包含了调用的函数名、传入的数据(分别放在name 和 data 中)
  • 支持回调和Promise两种风格
  • 下面给出官方文档中调用上述两个函数的代码。
wx.cloud.callFunction({
  // 云函数名称
  name: 'add',
  // 传给云函数的参数
  data: {
    a: 1,
    b: 2,
  },
  success(res) {
    console.log(res.result.sum) // 3
  },
  fail: console.error
})
//回调风格
wx.cloud.callFunction({
  // 云函数名称
  name: 'add',
  // 传给云函数的参数
  data: {
    a: 1,
    b: 2,
  },
  success(res) {
    console.log(res.result.sum) // 3
  },
  fail: console.error
})
  
//Promise风格
wx.cloud.callFunction({
  // 云函数名称
  name: 'add',
  // 传给云函数的参数
  data: {
    a: 1,
    b: 2,
  },
})
  .then(res => {
    console.log(res.result) // 3
  })
  .catch(console.error)

异步返回数据库结果

  • 在云函数中,我们通常是为了进行对数据库的调用。那么按照上面的方法写,我们会发现得出的结果都为null ,这是就需要用到 Promise 对象
  • Promise 对象的教程:教程地址
  • 基本框架如下:
exports.main = async (event, context) => new Promise((resolve, reject) => {
    resolve( Object );
})

简单来说,就是新建一个 Promise 对象,在大括号中完成函数,然后将需要的结果打包成Object 放入resolve 中,然后就可以在逻辑层用 res 对象得到结果。

项目查询实例

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const CloudDatabase = cloud.database();
const CloudCommand = CloudDatabase.command;
// 云函数入口函数
exports.main = async (event, context) => new Promise((resolve, reject) => {

  if (typeof event.blackList == "undefined") {
    var blackList = [];
  }
  else {
    var blackList = event.blackList;
  }

  if (typeof event.oderByWay == 'undefined') {
    var oderByWay = 'desc';
  }
  else {
    var oderByWay = event.oderByWay;
  }

  resolve(CloudDatabase.collection('dish')
    .where({
      _id: CloudCommand.nin(blackList)
    })
    .orderBy('rate.score', oderByWay).get());
})
exam:function(){
    wx.cloud.callFunction({
      name:'findDishByPrice'
    }).then(res => {
      console.log(res);
    })
  }

结果如下:
在这里插入图片描述
所以,我们用 res.result.data[index] 访问我们真正想要的集合信息

猜你喜欢

转载自blog.csdn.net/qq_43575267/article/details/88374096