【问题标题】:Node UnhandledPromiseRejectionWarning when saving to MongoDb保存到 MongoDb 时的节点 UnhandledPromiseRejectionWarning
【发布时间】:2020-04-13 21:51:34
【问题描述】:

节点新手-我正在尝试使用 Twit 包将我的一些推文从 Twitter API 保存到 mongo。

我已经使用 mongoose 连接到端口 27017 上的 mongodb,我编写的这段代码似乎将推文保存到我的数据库中,但是我似乎每次保存文档时都会收到此警告:

(node:9991) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 8)

这是我的代码:

const Tweet = require('./app/models/tweet.model.js');
const dbConfig = require('./config/database.config.js');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

mongoose.connect(dbConfig.url, {
    useNewUrlParser: true
}).then(() => {
    console.log("Successfully connected to the database");
}).catch(err => {
    console.log('Could not connect to the database. Exiting now...', err);
    process.exit();
});

var Twit = require("twit");

var config = require("./config/twitter.config");
var T = new Twit(config);


var params = {
  screen_name: "decade3uk",
  count: 2
};

T.get("statuses/user_timeline", params, gotData);

function gotData(err, data, response) {

  var tweets = data;

  for(var i=0;i<tweets.length;i++){

    const tweet = new Tweet({
      created_at:tweets[i].created_at,
      id_str:tweets[i].id_str,
      text:tweets[i].text
    });

    tweet.save()
        .then(entry => {
          response.send(entry);
        }).catch(err => {
          response.status(500).send({
            message: err.message || "Some error occurred while creating the Tweet."
          });
        });

  }

}

消除此错误的最佳做法是什么?

【问题讨论】:

    标签: javascript node.js twitter promise


    【解决方案1】:

    您为什么不尝试找出该异常来自哪里以及它到底是什么。您可以通过将以下代码添加到您的服务器文件中来找到它,以确保您了解导致异常的原因。

    process.on('unhandledRejection', (reason, promise) => {
       console.log("Reason: ",reason,"promise: ",promise);
    })
    

    【讨论】:

    • 发现问题。谢谢saiteja,可以在tweet.save()之后摆脱那个位
    猜你喜欢
    • 2020-02-18
    • 1970-01-01
    • 2017-08-09
    • 2016-02-13
    • 2021-01-07
    • 2020-03-08
    • 2022-01-20
    • 2020-03-24
    • 2018-12-09
    相关资源
    最近更新 更多