简体   繁体   中英

Not able to resolve promise chain error in Node.js

I have made a function it is actually having many asynchronous calls

function is something like this

const createOrUpdatePlan = (billPlans, serviceId, update) => {
  let billPlansWithId;
  let promises = [];
  if (!update) {
    billPlans.map(bp => {
      bp.serviceId = serviceId;
      return bp;
    });
    console.log(billPlans);
    return db.serviceBillPlans.bulkCreate(billPlans);
  } else {

     //first promise
    let findPromise = db.coachingClasses
      .findAll({
        attributes: ['billPlans'],
        where: {
          id: serviceId
        }
      })
      .then(previousBillPlans => {
        //creating new bill plans in edit class
        let newBillPlans = billPlans.filter(bp => !bp.id);

        if (newBillPlans.length > 0) {
          newBillPlans = newBillPlans.map(bp => {
            bp.serviceId = serviceId;
            return bp;
          });
          // console.log(newBillPlans);

           //second promise 
          let createPromise = db.serviceBillPlans
            .bulkCreate(newBillPlans)
            .then(newPlans => {
              let p1;
              billPlansWithId = billPlans.filter(bp => bp.id);
              if (newPlans) {
                newPlans.forEach(element => {
                  let object = {};
                  object.id = element.id;
                  (object.name = element.name),
                    (object.cycle = element.cycle),
                    (object.fees = element.fees);
                  billPlansWithId.push(object);
                });

              }
              console.log(billPlansWithId);
              billPlans = billPlansWithId;
              return billPlans;
            });
          promises.push(createPromise);
        }
      });
    promises.push(findPromise);
    return Promise.all(promises).then((arr) => arr[1] );
  }
};

I am calling this function in another function in which after this function call I am updating the data in another table which is received by this function

Currently what is happening in createOrUpdatePlan function first promise is running but after that in second promise where I am inserting data and after that in then

 .then(newPlans => {
          let p1;
          billPlansWithId = billPlans.filter(bp => bp.id);
          if (newPlans) {
            newPlans.forEach(element => {
              let object = {};
              object.id = element.id;
              (object.name = element.name),
                (object.cycle = element.cycle),
                (object.fees = element.fees);
              billPlansWithId.push(object);
            });

          }
          console.log(billPlansWithId);
          billPlans = billPlansWithId;
          return billPlans;
        });

This then block code is running after this function has returned data in another function

since I have written console.log in this then block so I am getting logs something like this

INSERT INTO `service_bill_plans` (`id`,`service_id`,`name`,`cycle`,`fees`,`created_at`,`updated_at`) VALUES (NULL,'17','Five Months Plan',5,4000,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP),(NULL,'17','Six Months Plan',6,5000,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP);
undefined
(node:8412) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): SequelizeValidationError: notNull Violation: coachingClasses.billPlans cannot be null
(node:8412) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
[ { id: 1, name: 'Monthly Plan', cycle: 1, fees: 1000 },
  { id: 2, name: 'Yearly Plan', cycle: 12, fees: 10000 },
  { id: 3, name: 'Two Months Plan', cycle: 2, fees: 1500 },
  { id: 4, name: 'Three Months Plan', cycle: 3, fees: 2500 },
  { id: 5, name: 'Four Months Plan', cycle: 4, fees: 3000 },
  { id: 148, name: 'Five Months Plan', cycle: 5, fees: 4000 },
  { id: 149, name: 'Six Months Plan', cycle: 6, fees: 5000 } ]

Since you can see data is inserted in the table in this function but after that in then block it is not returning before the returning data in this function .

I am really stuck with this promise chain not able to understand what should I do . Please give some hints

In any promise chain, every then'able block must return a data or a another promise. This is the thumb rule for a promise chain.

The function createOrUpdatePlan is returning a promise in "if" block, hence it is expected to return a promise in "else" block also. It is correct that you are returning Promise.all but you are combining inner promise and outer promise in Promise.all

db.coachingClasses    // findPromise is created here (main).
  .findAll({ ... })
  .then(previousBillPlans => {
     // createPromise is created here (inner promise); 

     // This then'able block must have a return data/promise - missing
   })

return Promises.all(); // mix of inner and outer makes no sense.

The expected promise chain is as below

return db.coachingClasses    // findPromise
  .findAll({ ... })
  .then(previousBillPlans => {
     // return createPromise
   })

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