节点JS异步/等待

时间:2019-07-01 02:08:58

标签: node.js mongodb mongoose

我收到未处理的承诺拒绝。

我只是想在调用res.send()之前等待insertParams函数完成。

这是我尝试过的:

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);
        }
    })
}

完整错误:

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.

3 个答案:

答案 0 :(得分:4)

根据insertOne()

  

返回:

     

如果没有通过回调,请保证

因此,您可以简单地返回Promise而无需传递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;
}

但是,返回的Promise解析为insertWriteOpResultObject

具有以下属性,请参阅参考链接以获取更多详细信息

{
    insertedCount:  Number  
    ops:            Array.<object>  
    insertedIds:    Object.<Number, ObjectId>   
    connection:     object  
    result:         object
}

答案 1 :(得分: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);
    });
  });
}

如果使用node-mongodb-native,则无需回调即可返回:

function insertParams(params) {
  // It will return `Promise`
  return db.collection('params').insertOne(params);
}

答案 2 :(得分:-1)

您正在async await中调用没有.catch()的catch。 您可以使用Promise,然后调用.then/.catch,使之更加痛苦

OR

只需从代码中删除.catch块 ,然后使用try / catch

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

});

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