如何在此nodejs代码中执行和处理Promise? (用户之前和之后的排行榜排名)

时间:2019-09-27 18:59:07

标签: node.js mongodb promise

我想在用户之前和之后显示排行榜排名。

文件Leaderboard.js:

exports.leaderboarduser = userName =>
  new Promise((resolve, reject) => {
    const player = user.findOne({ userName: userName });
    const next_player = user
      .find({ _id: { $ne: player._id }, score: { $gte: player.score } })
      .sort({ score: 1, userName: 1 })
      .limit(-1)[0];
    const previous_player = user
      .find({ _id: { $ne: player._id }, score: { $lte: player.score } })
      .sort({ score: -1, userName: -1 })
      .limit(-1)[0]
      .then(users => {
        resolve(users);
      })
      .catch(err =>
        reject({ status: 500, message: "Internal Server Error !" })
      );
  });

运行时:

  

(节点:18753)UnhandledPromiseRejectionWarning:RangeError   [ERR_HTTP_INVALID_STATUS_CODE]:无效的状态码:未定义       在ServerResponse.writeHead(_http_server.js:209:11)       在ServerResponse.writeHead(/root/game/node_modules/on-headers/index.js:44:26)       在ServerResponse._implicitHeader(_http_server.js:200:8)       在write_(_http_outgoing.js:585:9)       在ServerResponse.end(_http_outgoing.js:702:5)       在ServerResponse.send(/root/game/node_modules/express/lib/response.js:221:10)       在ServerResponse.json(/root/game/node_modules/express/lib/response.js:267:15)       在Leaderboard.leaderboarduser.then.catch.err(/root/game/routes.js:152:42)       在process._tickCallback(内部/进程/next_tick.js:68:7)(节点:18753)UnhandledPromiseRejectionWarning:未处理的承诺   拒绝。该错误是由抛出异步内部引起的   没有捕获块或拒绝承诺   未使用.catch()处理。 (拒绝ID:2)(节点:18753)[DEP0018]   DeprecationWarning:已弃用未处理的承诺拒绝。在   未来,未处理的承诺拒绝将终止   具有非零退出代码的Node.js进程。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

不确定您是否真的需要多个查询,因为我对您的数据库结构一无所知。这是排序后的代码:

exports.leaderboarduser = (userName) => {
    return new Promise(async (resolve, reject) => {
        try {
            const current_player = await user.findOne({ userName: userName });

            const next_playerResult = await user.find({ _id: { $ne: player._id }, score: { $gte: player.score } }).sort({ score: 1, userName: 1 }).limit(1);
            const next_player = next_playerResult[0] || {};

            const previous_playerResult = await user.find({ _id: { $ne: player._id }, score: { $lte: player.score } }).sort({ score: -1, userName: -1 }).limit(1);
            const previous_player = previous_playerResult[0] || {};
            resolve([current_player, next_player, previous_player]);        // change the order as per requirement
            // OR better send an object like: resolve({ current_player, next_player, previous_player });
        } catch (err) {
            reject(err);
        }
    });
}

问题是您没有正确调用异步函数。也没有捕获块来处理错误。我在promise中使用了 async / await 处理异步数据库调用。然后可以在项目中的某处调用此函数,如下所示:

leaderboarduser('testName')
    .then((users) => {
        console.log("users are: ", users);
    ...
    // do something with users
})
    .catch((err) => {
        console.log("Error: ", err);
    ...
    // handle error
});
猫鼬

limit()用于限制记录的数量。由于您只需要一条记录,因此应该通过 1 而不是 -1

希望这会有所帮助:)