【问题标题】:I am getting Promise <Pending> when using mongoose find() function使用 mongoose find() 函数时,我得到了 Promise <Pending>
【发布时间】:2020-02-28 12:28:23
【问题描述】:

我创建了一个从 MongoDB 获取所有产品列表的函数。我正在使用猫鼬包。我正在尝试控制台记录它,但相反,我得到了 Promise 。这是我的代码:-

router.get('/', function (req,res) {

    //Gets all the products being sold by the particular seller
    const allProducts = findAllProducts(userId);
    console.log(allProducts);
})

async function findAllProducts(sellerId) {
    try {
        let products = await Products.find( { seller: {
            Id: sellerId
        }});   
        return products;     
    } catch (error) {
        console.log(e);
    }
}

【问题讨论】:

  • 由于findAllProductsasync function,它返回一个承诺。你也必须await

标签: javascript node.js express mongoose promise


【解决方案1】:

你需要将 async/await 移到路由函数中:

router.get('/', async function (req,res) {

    //Gets all the products being sold by the particular seller
    const allProducts = await findAllProducts(userId);
    console.log(allProducts);
})

function findAllProducts(sellerId) {
    try {
        return Products.find( { seller: {
            Id: sellerId
        }});   

    } catch (error) {
        console.log(e);
    }
}

【讨论】:

  • 在这种情况下,您还应该在路由处理程序中移动try/catch - 否则它不会捕获任何异常。
猜你喜欢
  • 2021-08-04
  • 2022-12-03
  • 2018-11-16
  • 1970-01-01
  • 2019-12-23
  • 2020-07-09
  • 2017-10-16
  • 1970-01-01
  • 2023-03-21
相关资源
最近更新 更多