node.js - 获取承诺的价值

node.js - get value of 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});
  }
};

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

您需要修改 withDB() 以便它 returns 您想要的值:

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 以便它会拒绝返回的承诺并且调用者可以看到它。

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