node.js-获得承诺的价值

时间:2020-04-06 17:14:56

标签: javascript es6-promise

let { errors } = otherValdations(data);

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

       ..code...

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

如何获取'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});
  }
};

2 个答案:

答案 0 :(得分:0)

您需要修改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()处理程序中,您还需要执行一些操作,以便您的调用代码可以区分已经发送错误响应的错误路径和使用该值解析的情况。我不知道您希望它如何工作,但我输入了throw error,以便它将拒绝返回的诺言,并且呼叫者可以看到。

我从您的错误处理中注意到,您假设所有可能的错误都是由连接到DB的错误引起的。这里情况不同。如果operations(db)拒绝,那也将击中您的catch

答案 1 :(得分:-1)

Promise.all返回带有结果的数组。因此,您要么必须遍历结果,要么通过提供索引直接访问它们。