云函数调用数据库后返回小程序的result为null
发布于 5 年前 作者 zhengmin 10694 次浏览 来自 问答

云函数:

exports.main = async (event, context) => new Promise((resolve, reject) => {
  db.collection('cardList').add({
    data: {
      name : 'name'
    },
    success: function () {
      resolve({status : 1})
    }
  });
})

小程序:

wx.cloud.callFunction({
      name: 'addCard',
      data: {
        name : 'name'
      },
      complete: res => {
        console.log('callFunction test result: ', res)
      },
      success  : res => {
        console.log(res)
      }
    })

小程序中打印出来的是:

{errMsg: “cloud.callFunction:ok”, result: null, requestID: “e474bbe7-10e1-11e9-9884-525400192d0e”}

请问result为何返回的是 {status : 1}

但是官网的例子是可以输出的值

exports.main = (event, context) => new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(3333)
    }, 3000)
  })

{errMsg: “cloud.callFunction:ok”, result: 3333, requestID: “e474bbe7-10e1-11e9-9884-525400192d0e”}

3 回复

云函数处理数据库并根据处理结果返回前端:

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  try {
    let res =  await db.collection('tb_user').add({
      data: {
        openid: wxContext.OPENID,
        appid: wxContext.APPID,
        unionid: wxContext.UNIONID
      }
    })
    var code = 0
    var msg = 'success'
    if (res.errMsg != 'collection.add:ok') {
      code = 1
      msg = 'error'
    }
    return {
      code: code,
      msg: msg,
      data: {
        openid: wxContext.OPENID,
        appid: wxContext.APPID,
        unionid: wxContext.UNIONID,
        env: wxContext.ENV
      }
    }
  } catch (e) {
    console.error('err:',e)
    return {
      code: e.errCode,
      msg: 'error'
    }
  }
}

这样


exports.main = async (event, context) => {  


 

return await db.collection('cardList').add({      

     data: {        

        name: 'name',        

        }

   })

 


}

马上学习了一下 Promise  

https://segmentfault.com/a/1190000007032448


Promise接受一个「函数」作为参数,该函数的两个参数分别是resolve和reject。

这两个函数就是就是「回调函数」,由JavaScript引擎提供。

resolve函数的作用:在异步操作成功时调用,并将异步操作的结果,作为参数传递出去; reject函数的作用:在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去。

resolve传递出去的结果,外部函数并没有 接收到吧?

不知道我加个 return 对不对

exports.main = async (event, context) => return new Promise((resolve, reject) => {})

回到顶部