1

I am using nodejs

This is my function called createSchema:

const createSchema = () => {
  Business.findAll({
    raw: true,
  }).then((data) => {
    data.forEach((client) => {
      postgresDB.createSchema(client.code).then(() => {
        Object.keys(postgresDB.models).forEach((currentItem) => {
          postgresDB.models[currentItem].schema(client.code).sync();
        });
        console.log('Postgres schema created');
      }).catch(() => {
      });
    });
  }).catch((err) => {
    console.log('Warning:', err.message);
  });
};
createSchema();

I am calling this function, inside this post function

exports.createBusiness = (req, res) => {
  const business = {
    name: req.body.name,
    code: req.body.code,
    email: req.body.email,
  };
  Business.create(business)
    .then((rawbusinessData) => {
      createSchema()     // this is the function
        .then(() => { .  // i want to complete createSchema fully then only i want to execute this below stuffs
          const businessData = rawbusinessData.get({ plain: true });
          const loginDetails = {
            username: 'sameer',
            password: encrypt('sameer'),
          };
          const schemaLogin = postgresDB.models.login.schema(businessData.code);
          schemaLogin.create(loginDetails).then((loginData) => {
            console.log('loginData:', loginData);
          });
          res.status(200).send(businessData);
        });
    })
    .catch((err) => {
      console.log('err:', err);
    });
};

I am calling the first function inside my second post function called createBusiness,

I want to complete the createSchema function fully, then only i need to execute other then method() in my second function called createBusiness

See my code, i made a comment which needs to work first,

I tried with async await but not working!

4
  • 1
    return Business.findAll({. Missing return Commented Jun 7, 2018 at 9:56
  • Is postgresDB.models[currentItem].schema(client.code).sync(); a synchronous operation or does it return a Promise that needs to be resolved before running the code on the bottom? Commented Jun 7, 2018 at 9:58
  • it return a promise, i think so! Commented Jun 7, 2018 at 9:59
  • I put return still its not working as i expected. @NeilLunn Commented Jun 7, 2018 at 10:00

2 Answers 2

2

You're missing returning Promise's in quite a few places. You need to return all of them:

// No "block" implies return
const createSchema = () =>
  Business.findAll({ raw: true})
    .then((data) => 
      // wrap Promise.all and map() instead of forEach()
      Promise.all(
        data.map((client) =>
          postgresDB.createSchema(client.code).then(() => 
            // Again wrap Promise.all and map()
            Promise.all(
              Object.keys(postgresDB.models).map((currentItem) => 
                postgresDB.models[currentItem].schema(client.code).sync()
              )
            )
          )
        )
      )
    )
    .then(() => console.log("now I'm done"))
    //.catch((err) => console.log('Warning:', err.message));

So mostly wrapping Promise.all and using Array.map() to actually return the promises where you are iterating

The other thing is don't overuse blocks {}. Simply just return on the arrow function when you only have one thing in there anyway. Optionally drop the .catch() and just allow the errors from this function to throw. After you debug then you actually "should" remove that line and allow errors to throw.

Sign up to request clarification or add additional context in comments.

8 Comments

hi thanks for your answer, but still this code: schemaLogin.create(loginDetails).then((loginData) => { console.log('loginData:', loginData); }); executes first!
@MohamedSameer You sure? Put a log statement in createSchema too. Maybe it just returns something you're not expecting.
@MohamedSameer The code you are pointing to comes after the then() tacked onto the end of this function in your listing. I just put in a log for you so you can copy that one and see for certain when this code is done. I'm presuming everything is a Promise and just returning "every" function call. There's no way anything else fires first. Unless you broke your posted code as well.
@NeilLunn the message "now I'm done" its not showing on my server.
@MohamedSameer What message? That is not even in your code. The big problem here is that you just did not understand when you need to return evaluated promises. I certainly don't trust that you magically knew how to do that elsewhere in your code. Don't run any other code. Just run the one function you actually asked about. I'm not going to sit here all night an debug your entire program. Test the one function and then work out the rest of your problems separately.
|
0

Ideally, tour code should work. The issue happend may be because createSchema() function is not returning a promise.

     const createSchema = () => {
      Business.findAll({
        raw: true,
      }).then((data) => {
        data.forEach((client,index) => {

          postgresDB.createSchema(client.code).then(() => {
            Object.keys(postgresDB.models).forEach((currentItem) => {
              postgresDB.models[currentItem].schema(client.code).sync();
               if(index==data.length-1)
                return true;
            });
            console.log('Postgres schema created');
          }).catch(() => {
          });
        });
      }).catch((err) => {
        console.log('Warning:', err.message);
      });
    };

6 Comments

Return promise from createSchema (add return to the start of the method). The code of createSchema is already in the question. Also worth pointing out that async/await will also work once createSchema returns a promise.
I edited the answer and see whether it works. The idea is to detect the end of loop and return promise. Modify the code accordingly
Now in my second function, after createSchema(), then method not working.
const createSchema = async()=>{} change function to return a promise
Still the second function executes first, it doesnot waiting for first function to complete full
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.