Search code examples
javascriptes6-promise

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);
})

How can I get 'result' variable to be the value of the object returned in promise.all? This is the code for withDB function:

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});
  }
};

Solution

  • You need to modify withDB() so that it returns the value you want:

    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;
        }
    }
    

    In your catch() handler, you also need to do something so that your calling code can distinguish the error path where you've already sent an error response from the case where you're resolved with the value. I don't know exactly how you want that to work, but I put in a throw error so that it will reject the returned promise and the caller can see that.

    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.