Promise (pending) when calling async method inside a class from an async method of same class

Am using sequilizer and struggling because the method is forever in pending state.

The following is a simplified version of what I am trying to do. Basically, an API makes use of the below methods, by calling BatchProcessor, which was supposed to process the provided json.

I basically want BatchProcessor to get themeprice and themegate from FinalTheme method but the promise is forever pending.

export default {


  async FinalTheme(id) {

    return db.Themes.findOne({
      where: {
        ID: id
      },
      attributes: ["ThemeCost","ThemeGate"],

      limit: 1
    })
      .then(data => {

        if (data == null) {
          return -1;
        }

        return {
          cost: data["ThemeCost"],
          gate: data["ThemeGate"]
        };
      })
      .catch(err => {
        return false;
      });
  },


  async BatchProcessor(record, index_number) {

    const SQL ="SELECT * FROM themes";


    return db.sequelize
      .query(SQL, {

        type: db.sequelize.QueryTypes.SELECT
      })
      .then(themes => {
        // do we have data here?

        const totalThemes = themes.length;


          let lastAmount = record["Amount"]; 
          for (
            let counter = 0;
            counter < totalThemes - 1;
            counter++
          ) {


            const CustomerFinalTheme = this.FinalTheme(record["CustomerID"]); // FOREVER PENDING


          }



      })
      .catch(err => {
        console.log(JSON.stringify(err));
      });
  },

};

What am I doing wrong exaclty?

Answer

this.FinalTheme(… returns a promise and not the value you have to do:

this.FinalTheme(record["CustomerId"]) // where is the record assigned?
    .then(data => {
        const CustomerFinalTheme = data;
    })

also no need to use async when declaring the functions ie the following is ok:

FinalTheme(id) {
    return db.Themes.findOne({
    [...]
}

Leave a Reply

Your email address will not be published. Required fields are marked *