云开发get结果再for循环查询另一集合去更新前面get结果
发布于 6 年前 作者 chao96 7586 次浏览 来自 问答
  • 需求的场景描述(希望解决的问题)
  1. 查询返回用户所发照片的记录res;

  2. for循环根据每条记录里的openid去user集合里查询每个发照片人的用户头像和昵称;

  3. 再把每一位用户头像和昵称键值对追加到原来的res里;

  • 希望提供的能力
function getData(event, context) {
  return db.collection('photolist').get().then(res => {
    const db_user = db.collection('photouser')
    for (var i = 0, len = res.data.length; i < len; i++) {
      ures = db_user.where({ openid: res.data[i].openid }).get()
      res.data[i].avatarUrl = ures.data[0].avatarUrl
      res.data[i].nickName = ures.data[0].nickName
    }
    return res
  });
}
 
// 云函数入口函数
exports.main = async(event, context) => {
  if (event.type === 'add') {
    return add(event, context);
  }
 
  if (event.type === 'useradd') {
    return userAdd(event, context);
  }
 
  return getData(event, context);
}

返回结果:

{"errorCode":1,"errorMessage":"user code exception caught","stackTrace":"Cannot read property '0' of undefined"}

加上await后:

function getData(event, context) {
  return db.collection('photolist').get().then(res => {
    const db_user = link.collection('photouser')
    for (var i = 0, len = res.data.length; i < len; i++) {
      ures = await (db_user.where({ openid: res.data[i].openid }).get())
      res.data[i].avatarUrl = ures.data[0].avatarUrl
      res.data[i].nickName = ures.data[0].nickName
    }
    return res
  });
}
 
// 云函数入口函数
exports.main = async(event, context) => {
  if (event.type === 'add') {
    return add(event, context);
  }
 
  if (event.type === 'useradd') {
    return userAdd(event, context);
  }
 
  return getData(event, context);
}

返回结果:

{"errorCode":1,"errorMessage":"user code exception caught","stackTrace":"await is not defined"}

求大神指点,这个到底怎么写?

急急急,这个问题不弄好,老板不让春节回家!!!!!

2 回复

async function getData(event, context) {

  const res= await db.collection('photolist').get();


       const db_user = db.collection('photouser')

    for (var i = 0, len = res.data.length; i < len; i++) {

      ures =await db_user.where({ openid: res.data[i].openid }).get()

      res.data[i].avatarUrl = ures.data[0].avatarUrl

      res.data[i].nickName = ures.data[0].nickName

    }

  return res


}

 

// 云函数入口函数

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

  if (event.type === 'add') {

    return add(event, context);

  }

 

  if (event.type === 'useradd') {

    return userAdd(event, context);

  }

 

  return await  getData(event, context);

}

这个  userAdd    add  云函数?还是啥


云函数 调用 云函数请看

https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-server-api/functions/callFunction.html

可以了,非常感谢@半寸灰

回到顶部