异步函数中未定义的返回数据

时间:2019-05-16 15:35:35

标签: node.js async-await

我正在尝试进行数据库搜索,然后将所有数据作为数组返回,但是等待部分返回的是未定义

我已经console.logged数组,并很好地打印了结果,但是在外面说未定义

async function followUsersIds(user_id) {

    const following = await Follow.find({ "user": user_id })
        .select({ '_id': 0, '__v': 0, 'user': 0 }) //Evitar que traiga esos campos
        .exec((err, follows) => {
            if (err)
                return res.status(500).json({ ok: false, msg: `Error ${err}` })

            let following_clean = [];
            follows.forEach((follow) => {
                following_clean.push(follow.user_followed);
            });

            return following_clean;
        });


    return {
        following
    }
}

这是电话:

followUsersIds(user_id)
                    .then((value) => {
                        console.log(value);
                        return res.status(200).json({
                            ok: true,
                            usuarios,
                            users_following: value.following,
                            total: conteo,
                            pages: Math.ceil(conteo / limite)
                        });
                    })
                    .catch(err => { return res.json({ ok: false, msg: `Error ${err}` }) })

但是我没有得到“ users_following”,如果我在控制台上记录“ value”,它会显示{以下内容:undefined}

1 个答案:

答案 0 :(得分:0)

您正在混合使用回调和异步/等待语法

这是async / await语法:

const following = await Follow.find({ "user": user_id })

这是回调语法:

exec((err, follows) => {

try {
  // We get a Promise object from exec() that we resolve
  // We use a || [] to initialize following with an empty array
  // in case nothing got foung in database
  const following = (await Follow.find({
      user: user_id,
    })
    .select({
      _id: 0,
      __v: 0,
      user: 0,
    })
    .exec()) || [];

  // We build a new array containing only the wanted data
  const following_clean = following.map(x => x.user_followed);

  console.log(following_clean);
} catch (err) {
  // Handle the error
  return res.status(500).json({
    ok: false,
    msg: `Error ${err}`,
  });
}