使用猫鼬find()函数时出现Promise <Pending>

时间:2019-11-02 14:57:13

标签: javascript node.js express mongoose promise

我创建了一个从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);
    }
}

1 个答案:

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