简体   繁体   中英

Can I await 2 async actions with 1 await?

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

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

In your comments you have mentioned you want to run two async calls after the other using await.

The other answer has used promises to show you this behaviour. How ever using await you can run two async calls much cleanly! just do:

async twoAsyncCalls(){

    let firstResult = await first();
    //Things to do after first

    let secondResult = await second();
   //Things to do after second

    //To catch any async errors surround this code with a try catch block!

    return {/* return anything here*/}
    //This will be wrapped in a promise

}

So to answer your question you cannot sequentially run 2 async calls one after the other using just one await! You need 2 await statements.

Your code should be changed to this usage

const db = await require('../db/db.js').db; 
const existingUser = await db.Person.findOne({where : {email : body.email}});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM