首页 > 解决方案 > node.js - 获取承诺的价值

问题描述

let { errors } = otherValdations(data);

withDB(async (db) => {
    return Promise.all([

       ..code...

    ]).then(() => {
        return {
            errors,
            isValid: isEmpty(errors),
        }
    })
}, res).then((result) => {
    console.log(result);
})

如何让“结果”变量成为 promise.all 中返回的对象的值?这是 withDB 函数的代码:

const withDB = async (operations, res) => {
try {
    const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
    const db = client.db('app');

    await operations(db);

    client.close();
  } catch (error) {
    res.status(500).json({ message: 'Error connecting to db', error});
  }
};

标签: javascriptes6-promise

解决方案


您需要进行修改withDB(),使其返回您想要的值:

const withDB = async (operations, res) => {
    try {
        const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
        const db = client.db('app');

        let result = await operations(db);

        client.close();
        return result;
    } catch (error) {
        res.status(500).json({ message: 'Error connecting to db', error});
        throw error;
    }
}

在您的catch()处理程序中,您还需要做一些事情,以便您的调用代码可以区分您已经发送错误响应的错误路径与您使用该值解析的情况。我不确切知道您希望它如何工作,但我输入了 athrow error以便它拒绝返回的承诺并且调用者可以看到。

I notice from your error handling that you are assuming all possible errors are causing by an error connecting to the DB. That is not the case here. If operations(db) rejects, that will also hit your catch.


推荐阅读