2

I have a node module that exports a promise and resolves a database connection. When it resolves I use the connection to query records which is another async operation. Can I do both of these async actions with 1 await?

In this case the querying async call is dependent on the async promise resolving to a db connection.

Module

module.exports = {
  db: new Promise((acc, rej) => {
      if (!db.authenticated) {
        sequelize.authenticate()
        .then((res) => {
            db.authenticated = true;
            acc(db);
        })
        .catch((err) => {
            rej(err)
        });
      } else {
        acc(db);
      }
  })
};

usage

const db = require('../db/db.js').db;
const existingUser = await db.Person.findOne({where : {email : body.email}});
TemporaryFix
  • 2,008
  • 3
  • 30
  • 54
  • 1
    Could you clarify this sentence? `query, another async operation, records`. Not sure what you're asking. – Geuis Mar 27 '19 at 00:22
  • 1
    querying is another async operation. – TemporaryFix Mar 27 '19 at 00:22
  • 1
    Does one action rely on the output of the other? If yes, then the answer is you cannot perform both actions at the same time. – FThompson Mar 27 '19 at 00:24
  • 1
    Use `await Promise.all([someCall(), anotherCall()]);` – ABC Mar 27 '19 at 00:25
  • Possible duplicate of [How can I wait for set of asynchronous callback functions?](https://stackoverflow.com/questions/10004112/how-can-i-wait-for-set-of-asynchronous-callback-functions) – Heretic Monkey Mar 27 '19 at 00:42

1 Answers1

6

In response to my comment using await Promise.all([first(), second()]);:

The promise.All() method will return a single promise that finally resolves when all the promises pass as an iterable or when the iterable does not contain any promises. It will reject with the reason of the first promise that rejects.

Example

async function one() {
  return new Promise(resolve => {
    resolve('One')
  })
}

async function two() {
  return new Promise(resolve => {
    resolve('Two')
  })
}

async function run() {
  return await Promise.all([one(), two()]); // One await
}

run().then((response) => {
  // Access Individually
  console.log(response[0]); // One
  console.log(response[1]); // Two
  // Access Together
  console.log(response);
})

And to respond to your recent comment. To pass the value from one promise to the other, if the second function is dependent on that parameter. We might do something like this.

Example 2

async function first() {
  return new Promise(resolve => {
    resolve('First') // Resolve 'first'
  })
}

async function second(response) {
  return new Promise(resolve => {
    resolve(response); // first() ran, then we appended '& second', then resolve our second response
  })
}

async function run() {
  // Wait for first() response, then call second() with response + append 'second'
  return await first().then((response) => second(response + ' & second'))
}

run().then((response) => {
  // Output: first & second
  console.log(response)
})

Documentation: promise.All() - MDN

ABC
  • 2,068
  • 1
  • 10
  • 21
  • 1
    What if the second call is dependent on the first one's result? – TemporaryFix Mar 27 '19 at 00:57
  • @Programmatic Good question, check my updated post please, and tell me if that was what you were asking. – ABC Mar 27 '19 at 01:10
  • 1
    @Raymond I have one question, as TemporaryFix said, async second() depend on first() and all these two method is a async HttpClient call, i used your solution while it didn't work in my case. [Here](https://stackoverflow.com/questions/58706052/how-to-use-js-async-await-in-mutiple-async-requests) is my question, can you have a look? – Rollsbean Nov 06 '19 at 04:47
  • @KDFinal Second example if you notice `first()` is called then we invoke `then()`, that means the `second()` function call is depending on the first. – ABC Feb 10 '20 at 02:02
  • @KDFinal Do you still need help with that post? – ABC Oct 22 '20 at 21:25