-2

My function called createUser():

const createUser = () => {
    return new Promise(async (resolve, reject) => {
        var data = await Home.findAll({ raw: true })
        await data.forEach(async (client) => {
            await postgresDB.createSchema(client.code).then(async () => {
                await Object.keys(postgresDB.models).forEach(async (currentItem) => {
                    await postgresDB.models[currentItem].schema(client.code).sync();
                });
            });
        });
        resolve('Postgres schema created')
    });
} 

My nodejs api:

exports.createBusiness = (req, res) => {
  const business = {
    name: req.body.name,
    code: req.body.code,
    email: req.body.email,
  };
  Business.create(business)
    .then((rawbusinessData) => {
      createUser() // this needs to completed full then only i need to move to below then function


        .then(() => {
          const businessData = rawbusinessData.get({ plain: true });
          const loginDetails = {
            username: 'sameer',
            password: encrypt('sameer'),
          };
          postgresDB.models.login.schema(businessData.code).create(loginDetails)
            .then((loginData) => {
              console.log('loginData:', loginData);
              return res.status(200).send(loginData);
            }).catch((err) => {
              console.log('error while create schema:', err);
            });
        });
    })
    .catch((err) => {
      console.log('err:', err);
    });
};

I dont know whats the problem is, i am struggling for more than three days.

Is i am using correct syntax? or is it good to use only promises?

Mohamed Sameer
  • 2,998
  • 3
  • 22
  • 51
  • If you are using `async`/`await`, why are there so many `then` calls in your code? – Bergi Jun 23 '18 at 09:38
  • Also, [don't use the `Promise` constructor](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jun 23 '18 at 09:40

2 Answers2

0

forEach returns undefined, awaiting that does not await the async functions it iterated over. Instead map to an array of promises and use Promise.all to await them all:

await Promise.all(Object.keys(postgresDB.models).map(async (currentItem) => {
      /*...*/
}));

Additionally using new Promise inside of an async function makes no sense at all, the following:

const createUser = () => {
  return new Promise(async (resolve, reject) => {

Can be actually:

async function createUser() {
  //...
}

And then just return the result at the end.


You also have to

return User.create(loginDetails) 

so that it gets chained into the parent promise.


How i would do that:

async function createUser() {
  var data = await Home.findAll({ raw: true })
  await Promise.all(data.map(async (client) => {
    await postgresDB.createSchema(client.code)
    await Promise.all(Object.keys(postgresDB.models).map(currentItem => 

         postgresDB.models[currentItem].schema(client.code).sync();
    ));
  }));        
  return 'Postgres schema created';
} 

//------

exports.userSignup = async (req, res) => {
  try {
    await createUser();
    const loginDetails = {  username: 'stackoverflow' };
    const data = await User.create(loginDetails) 
    res.status(200).send(data);
  } catch(err) {
    console.log(err);
    res.status(500).send("")
 }
};
Community
  • 1
  • 1
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

You can't await a forEach like that - you need to map the promises to an array and use Promise.all instead. Also, don't construct and return a Promise when you already have a Promise from another call - instead, simply return the Promise from that other call.

Convert both forEachs into Promise.all calls. For example:

const createUser = async () => {
  var data = await Home.findAll({ raw: true });
  const clientPromises = data.map(async ({ code }) => {
    await postgresDB.createSchema(code);
    return Promise.all(postgresDB.models.map((currentItem) => (
      postgresDB.models[currentItem].schema(code).sync()
    )));
  });
  await Promise.all(clientPromises);
  console.log('Postgres schema created');
} 
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320