簡體   English   中英

節點 UnhandledPromiseRejectionWarning 保存到 MongoDb

[英]Node UnhandledPromiseRejectionWarning when saving to MongoDb

新節點-我正在嘗試使用 Twit package 將我的一些推文從 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."
          });
        });

  }

}

擺脫此錯誤的最佳做法是什么?

你為什么不試着找出那個異常來自哪里以及它到底是什么。 您可以通過將以下代碼添加到您的服務器文件中來找到它,以確保您了解導致異常的原因。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM