1

I have a chain of promises in my backend and i need to access the result of the first promise in the second one

 mongo.connect()
    .then((client) => {
      return circolari.infiniteScroll(client, currCirc)
    })
    .then(({ data, client }) => {
      mongo.close(client)
      res.send(data)
    })
    .catch(error => res.sendStatus(error.message))

I need to access client to close the connection in the second promise. Right now to achieve that I resolve in circolari.infiniteScroll(client, currCirc) an object like this:

resolve({
    data: data,
    client: client
})

With this workaround it works, but I think there's a better way to do it, thank you.

Mattia
  • 85
  • 1
  • 6
  • You can use `async` / `await`: `const client = await mongo.connect();` then `const data = await circolari.infiniteScroll(client, currCirc);` then `await mongo.close(client);` and finally `res.send(data);` –  Sep 23 '19 at 19:12

1 Answers1

0

You can make it a little bit shorter:

mongo.connect()
.then(client => circolari.infiniteScroll(client, currCirc)))
.then(({ data, client }) => {
      mongo.close(client);
      res.send(data);
})

Or using await and async:

async function returnResponse(res) {
    let client;
    try {
        client = await mongo.connect();
        const data = await circolari.infiniteScroll(client, currCirc);
        res.send(data);
    } catch (err){
        res.sendStatus(err.message)
    } finally {
        await mongo.close(client); // close connection in every case
    }

}
foo();
Mexxx
  • 61
  • 5
  • Question: is it possible that there would be an error in the mongo.close(), so it should be in the original try block? Why put it in the finally block? – Maiya Sep 23 '19 at 19:51
  • Actually, yes. Error might be in closing connection also, you right. Finally is for doing database closing in every case. You can put it in try also, but in catch you should also use it. So there is a place where finally comes – Mexxx Sep 23 '19 at 20:23