1

I am getting an Unhandled promise rejection.

I am simply trying to await for the function insertParams to finish before calling res.send().

Here is what I have tried:

app.get('/', async (req, res) => {
    let queries = {hello: 'testing'};
    const paramResult = await insertParams(queries)
      .catch(err => {
        console.log(err);
      })
    res.send('Hello world!');
});

async function insertParams(params) {
    return db.collection('params').insertOne(params, (error, success) => {
        if (error) {
            console.log('Error: ' + error);
        }
        else {
            console.log('Success: ' + success);
        }
    })
}

The full error:

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(). (rejection id: 1)
(node:13601) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
user10181542
  • 1,210
  • 3
  • 16
  • 37

2 Answers2

4

According to insertOne()

Returns:

Promise if no callback passed

So, you can simply return the Promise without passing in the callback

app.get('/', async (req, res) => {
    try {
        let queries = {hello: 'testing'};
        const paramResult = await insertParams(queries);

        // the `paramResult` will be of type `insertWriteOpResultObject`
        console.log(paramResult); 

        res.send('Hello world!');
    } catch(err) {
        console.log(err);
    }
});

function insertParams(params) {
    // no callback needed
    let promise = db.collection('params').insertOne(params);

    return promise;
}

However, the returned Promise resolves to insertWriteOpResultObject

Which has the following properties, please see reference link for more detail

{
    insertedCount:  Number  
    ops:            Array.<object>  
    insertedIds:    Object.<Number, ObjectId>   
    connection:     object  
    result:         object
}
Neverever
  • 15,890
  • 3
  • 32
  • 50
0
app.get('/', async (req, res) => {
  let queries = {
    hello: 'testing'
  };
  // 3. You should use `try catch` to handle `await` error.
  try {
    // 4. The return is the value that the `Promise` resolved.
    const success = await insertParams(queries);
    res.send('Hello world!');
  } catch (err) {
    // 5. Handle error here.
    console.log(err);
  }
});

// 1. You should not use `async` without `await`.
function insertParams(params) {
  // 2. You should make callback to `Promise`.
  return new Promise((resolve, reject) => {
    db.collection('params').insertOne(params, (error, success) => {
      if (error) {
        reject(error);
        return;
      }
      resolve(success);
    });
  });
}

If using node-mongodb-native, just return without callback:

function insertParams(params) {
  // It will return `Promise`
  return db.collection('params').insertOne(params);
}
Bugtaker
  • 321
  • 1
  • 5
  • 1
    Doesn't this database have a built-in promise interface that should be used rather than doing your own promisifying? – jfriend00 Jul 01 '19 at 05:29
  • @jfriend00 yes, of course. But, it did not mention which driver it was using. if using [node-mongodb-native](https://github.com/mongodb/node-mongodb-native), just return without callback. – Bugtaker Jul 01 '19 at 07:44